CSS :nth-child() Pseudo-class
- Previous page :not()
- Next Page :nth-last-child()
- Go Up One Level CSS Pseudo-class Reference Manual
Definition and Usage
CSS :nth-child(n)}}
pseudo-class to match as the n an element that is any child element of
This pseudo-class matches elements based on their index in the child list of their parent element.
n can be a number/index, a keyword (odd
or even
) or a formula (such as an + b)
Tip:View :nth-of-type()
pseudo-class to select as a child element of its parent elementsame type (tag name)of the n an element that is a child of the same type (element name).
Example
Example 1
How to use :nth-child()
Pseudo-class:
/* Select every fourth element in any group of sibling elements */ :nth-child(4) { background-color: yellow; } /* Select the second element among the div sibling elements */ div:nth-child(2) { background-color: red; } /* Select the second li element in the list */ li:nth-child(2) { background-color: lightgreen; }
Example 2
odd
and even
Is a keyword that can be used to match child elements with odd or even indices (the index of the first child element is 1).
Here, we specify different background colors for <p> elements with odd and even indices:
p:nth-child(odd) { background-color: red; } p:nth-child(even) { background: lightgreen; }
Example 3
Using the formula (an + b) Description:a Represents an integer step, n is all non-negative integers starting from 0,b Is an integer offset.
Here, we specify the background color for all <p> elements whose index is a multiple of 3 (to select the third, sixth, ninth, etc. elements):
p:nth-child(3n+1) { background-color: red; }
Example 4
Here, we specify the background color for all <p> elements whose index is a multiple of 3. Then we subtract 1 (to select the first, fourth, seventh, etc. elements):
p:nth-child(3n-1) { background-color: red; }
CSS syntax
:nth-child(index | odd | even | an+b) { css declarations; }
Technical details
Version: | CSS3 |
---|
Browser support
The numbers in the table specify the first browser version to fully support the pseudo-class.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
- Previous page :not()
- Next Page :nth-last-child()
- Go Up One Level CSS Pseudo-class Reference Manual