CSS3 :nth-child() selector
Complete CSS Selector Reference Manual
Example
Specify the background color of the 2nd child element of the parent that each p element matches:
p
:nth-child
(2)
{
background:
#ff0000
;
}
Try it »
Definition and Usage
:nth-child(n) selector matches the nth child element of the parent, with no restriction on element type.
n It can be a number, a keyword, or a formula.
Tip: SeeSelector. This selector matches the nth sibling element of the same type.
Syntax
element:nth-child(n)
elementis the HTML element you want to select.nis a parameter that can be a keyword (such asoddoreven), or an expression (such as2n+1).
The keywords odd and even
oddSelect child elements in odd positions.evenSelect child elements in even positions.
Browser support
The numbers in the table indicate the first browser version that supports this property.
| Selector | |||||
|---|---|---|---|---|---|
| :nth-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
More examples
Example 1
Odd and even can be used as keywords to match child elements whose index is odd or even (the first child node has index 1). Here we assign two different background colors to odd and even p elements:
p
:nth-child
(
odd
)
{
background:
#ff0000
;
}
p
:nth-child
(
even
)
{
background:
#0000ff
;
}
Try it »
Example 2
Using the formula (an+b). Description: a represents the size of a cycle, N is a counter (starting from 0), and b is the offset. Here we specify a background color for all p elements whose index is a multiple of 3:
p
:nth-child
(3
n
+0)
{
background:
#ff0000
;
}
Try it »