The nth-of-type pseudo-class
The nth-of-type pseudo-class selects
an element that is an nth child of a given type.
That is, if I write h2:nth-of-type(4)
- there will be 4th h2 in the
parent (unlike
nth-child,
which will only find the h2 that is
the 4th elements in the parent).
Syntax
selector:nth-of-type(number | odd | even | expression){
}
Values
| Value | Description |
|---|---|
| number |
A positive number starting with 1. It
specifies the number of the element we want
to access. Numbering of elements begins
with 1.
|
odd |
Odd elements. |
even |
Even elements. |
| expression |
You can create special expressions with
the letter n, which stands for all integers
from zero (not one) to infinity. So,
2n means all even numbers (starting
from the second).
How to understand this? We sequentially substitute into n
the numbers from 0 and so on: if n = 0,
then 2n will give 0 - there is no such element
(numbering of elements starting from 1),
if n = 1, then 2n gives 2 - the second
element, if n = 2, 2n gives 4 - the fourth
element. If you write 3n, it will be every
third element (starting from the third),
and so on.
|
Example
Let's find h2, which is 2nd
h2 in the parent:
<div>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
</div>
h2:nth-of-type(2) {
color: red;
}
:
Example
Let's find all even h2:
<div>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
</div>
h2:nth-of-type(even) {
color: red;
}
:
Example
Let's find all odd h2:
<div>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
<h2>header</h2>
<p>paragraph</p>
</div>
h2:nth-of-type(odd) {
color: red;
}
: