CSS :nth-child() Selector
Example
/* sets the background color to red if the p element is its parent's second child */
p:nth-child(2) {
background-color: red;
}
Meaning
The :nth-child() selector selects the element that is the nth child of its parent.
Note: That, in the element:nth-child() syntax, the child count includes children of any element type; but it is considered a match only if the element at that child position is of the specified element type.
Version: CSS3
Standard Syntax
:nth-child(n|odd|even|An+B) {
css declarations;
}
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Status
Parameter values
The following table describes the values of this selector parameter.
Value | Description |
---|---|
n | Specifies the number to selects the element that is the nth child of its parent. |
odd | Defines elements whose numeric position in a series of siblings is odd: 1, 3, 5, etc. |
even | Defines elements whose numeric position in a series of siblings is even: 2, 4, 6, etc. |
An+B | Defines elements in a list whose indices match those found in a custom pattern of numbers, defined by An+B, where:
|
More Example
Example
/* sets the background color to red if the p element is its parents even childs(2, 4, 6, etc.) */
p:nth-child(even) {
background-color: red;
}
Example selectors
tr:nth-child(odd)
ortr:nth-child(2n+1)
-
Represents the odd rows of an HTML table: 1, 3, 5, etc.
tr:nth-child(even)
ortr:nth-child(2n)
-
Represents the even rows of an HTML table: 2, 4, 6, etc.
:nth-child(7)
-
Represents the seventh element.
:nth-child(5n)
-
Represents elements 5 [=5×1], 10 [=5×2], 15 [=5×3], etc. The first one to be returned as a result of the formula is 0 [=5x0], resulting in a no-match, since the elements are indexed from 1, whereas
n
starts from 0. This may seem weird at first, but it makes more sense when theB
part of the formula is>0
, like in the next example. :nth-child(n+7)
-
Represents the seventh and all following elements: 7 [=0+7], 8 [=1+7], 9 [=2+7], etc.
:nth-child(3n+4)
-
Represents elements 4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], etc.
:nth-child(-n+3)
-
Represents the first three elements. [=-0+3, -1+3, -2+3]
p:nth-child(n)
-
Represents every
<p>
element in a group of siblings. This selects the same elements as a simplep
selector (although with a higher specificity). p:nth-child(1)
orp:nth-child(0n+1)
-
Represents every
<p>
that is the first element in a group of siblings. This is the same as the:first-child
selector (and has the same specificity). p:nth-child(n+8):nth-child(-n+15)
-
Represents the eighth through the fifteenth
<p>
elements of a group of siblings.