The CSS3 nth-child pseudo-class is a powerful CSS3 selector that solves many problems encountered by web developers while trying to stylize certain elements based on their position in the DOM tree. As its name says, this pseudo-class selects an element if this element is the nth-child of its parent. This kind of selector accepts four types of values:
- the keyword
even
(for even elements) - the keyword
odd
(for odd elements) - the
n
index, starting from 1 - the
an+b
formula, wheren
is a literal constant anda
andb
are numbers.
Some examples:
tr:nth-child(odd) { background: #eee; }
The above code selects all tr
elements that are odd. But we can also selects other indexes, like so:
tr:nth-child(4) { background: #eee; }
This code selects the 4th tr
element. If we want to perform a repeated selection, for example by selecting all tr
elements that are multiples of 3, we can write this formula:
tr:nth-child(2n+1) { background: #eee; }