CSS :nth-child() Selector - Select by Position
Master the :nth-child() CSS selector for zebra-striping tables, selecting every Nth element, and building complex positional patterns with the An+B formula.
Detailed Explanation
The :nth-child() Selector
The :nth-child() pseudo-class selects elements based on their position among siblings. It accepts a formula, keyword, or specific number as its argument.
Syntax
:nth-child(An + B) { }
Where A is the cycle size (step), n is a counter starting from 0, and B is the offset.
Common Patterns
| Pattern | Matches | Use Case |
|---|---|---|
:nth-child(odd) |
1st, 3rd, 5th... | Zebra-striped tables |
:nth-child(even) |
2nd, 4th, 6th... | Alternating row colors |
:nth-child(3) |
Only the 3rd child | Specific positioning |
:nth-child(3n) |
Every 3rd (3, 6, 9...) | Column-based layouts |
:nth-child(3n+1) |
1st of every 3 (1, 4, 7...) | First in each row |
:nth-child(n+4) |
4th and beyond | Skip first few items |
:nth-child(-n+3) |
First 3 only | Select a range |
Zebra-Striped Table
tr:nth-child(even) {
background-color: #f5f5f5;
}
Select First N Elements
/* First 5 items only */
li:nth-child(-n+5) {
font-weight: bold;
}
Select a Range
/* Items 3 through 7 */
li:nth-child(n+3):nth-child(-n+7) {
background: yellow;
}
:nth-child vs :nth-of-type
:nth-child() counts ALL siblings regardless of type. :nth-of-type() counts only siblings of the same element type:
<div>
<span>A</span>
<p>B</p> <!-- p:nth-child(2) AND p:nth-of-type(1) -->
<p>C</p> <!-- p:nth-child(3) AND p:nth-of-type(2) -->
</div>
Specificity
:nth-child() has specificity (0, 1, 0) — the same as a class selector.
Use Case
The :nth-child() selector is essential for creating zebra-striped tables, alternating card backgrounds, grid layouts where items in specific positions need different styling, pagination indicators, and any pattern where element position determines visual treatment. It eliminates the need for manually adding classes to alternating elements.