HTML and CSS Reference
In-Depth Information
Matching odd and even children is a common operation, so the keywords
odd
and
even
can also be used to match every other row in a table, for example.
tr:nth-child(even) {} /* even table rows */
tr:nth-child(odd) {} /* odd table rows */
As shown, the argument to
:nth-child()
can be an integer, the keywords
even
or
odd
, or an expression in the form of
an+b
. In the expression form, the keyword
n
is a
counter that iterates through all the child elements. The counter might be negative; in
that case, the iteration occurs backward. It can be used to select a specific number of
first children.
p:nth-child(-n+3) {} /* first three children */
The math and arguments used together with
:nth-child()
are also valid for the next
three pseudo-classes, all of which start with
:nth
.
nth-of-type
The
:nth-of-type(an + b)
pseudo-class matches the
b
th element of the selected type
after the siblings of that type have been divided into groups of
a
elements.
p:nth-of-type(2) {} /* second paragraph sibling */
p:nth-of-type(2n) {} /* even paragraph siblings */
p:nth-of-type(2n+1) {} /* odd paragraph siblings */
The behavior of this pseudo-class is similar to
:nth-child
, but it matches siblings
of the same type of the specified element instead of matching children of the specified
element.
<div>
<em>Text</em>
<p>Odd</p>
<p>Second and even</p>
<p>Odd</p>
</div>
Similar to the other
:nth
pseudo-classes, the keywords
odd
and
even
can be used to
match siblings of the same type whose index is odd or even.
p:nth-of-type(even) {} /* even paragraph siblings */
p:nth-of-type(odd) {} /* odd paragraph siblings */