CSS3 :nth-child()
Selector
Complete CSS Selectors Reference
Example
Specify the background color of the second child element of each p
element's parent:
p:nth-child(2) {
background: #ff0000;
}
Definition and Usage
The :nth-child(n)
selector matches the nth child element in any parent element, regardless of the element type.
n can be a number, a keyword, or a formula.
Tip: See Selector. This selector matches the nth sibling element of the same type.
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Selector | |||||
---|---|---|---|---|---|
:nth-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
More Examples
Example 1
Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1).
Here, we specify two different background colors for odd and even p
elements:
p:nth-child(odd) {
background: #ff0000;
}
p:nth-child(even) {
background: #0000ff;
}
Example 2
Using the formula (an+b). Description: a represents a cycle size, n is a counter (starts at 0), and b is an offset value.
Here, we specify the background color for all p
elements whose index is a multiple of 3:
p:nth-child(3n+0) {
background: #ff0000;
}