CKTIS / CSS
:nth-child() — selection by position
The :nth-child() pseudo-class selects elements by their position among siblings. It supports An+B patterns and optional filtering with of S.
Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required
Syntax
:nth-child(An+B)
:nth-child(odd)
:nth-child(even)
:nth-child(An+B of S):nth-child() counts elements from 1 in tree order, separately for each parent. Text and comments do not occupy positions; hidden elements still count.
In An+B, coefficients A and B are integers, and n takes values 0, 1, 2, …; only positive positions match. odd means 2n+1, even means 2n, 3 selects the third element, and -n+3 selects the first three.
Without of S, all sibling elements count. S is a selector list: :nth-child(2 of .item) first filters by .item, then selects the second result. In contrast, .item:nth-child(2) requires the second element overall to have class .item. :nth-of-type() counts siblings of the same element type, not the same class.
Specificity is (0,1,0) plus the specificity of the most specific selector in S, if supplied. In the example, only C should be highlighted: the second .item, although it is the third list element.
Examples
<!doctype html>
<meta charset="utf-8">
<title>:nth-child()</title>
<style>
#items > :nth-child(2 of .item) {
color: white;
background-color: navy;
}
</style>
<ul id="items">
<li class="item">A</li>
<li>B</li>
<li class="item">C</li>
<li class="item">D</li>
</ul>Result
C: color rgb(255, 255, 255); background-color rgb(0, 0, 128)
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.