:nth-child()
Matches children by their position: the third, every even one, every third one.
Syntax
selector:nth-child(an+b) { … }Parameters
| Parameter | Type | Description |
|---|---|---|
| n | number | A position counted from 1: `:nth-child(3)`. |
| odd | even | keyword | Odd or even positions. |
| an+b | formula | A formula: n takes the values 0, 1, 2…; `3n` is every third, `-n+2` is the first two. |
Examples
Striped table rows:
<style>
tr:nth-child(even) { background: whitesmoke; }
td { padding: 4px 12px; }
</style>
<table>
<tr><td>Anna</td><td>$25</td></tr>
<tr><td>Oleg</td><td>$40</td></tr>
<tr><td>Maria</td><td>$15</td></tr>
<tr><td>Ivan</td><td>$30</td></tr>
</table>Every third item and the first two:
<style>
li:nth-child(3n) { color: crimson; }
li:nth-child(-n+2) { font-weight: bold; }
</style>
<ol><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li></ol>Notes
Positions are counted among all children, whatever their tag. :nth-last-child() counts from the end. To count only elements of one type, use :nth-of-type().
See also
- :nth-of-type() — Like `:nth-child()`, but counts only siblings with the same tag.
- :first-child — Matches an element that is the first child of its parent.
- :last-child — Matches an element that is the last child of its parent.
Related recipes
In the tutorial
- Pseudo-classes — Styles for element states and positions — hover, focus, links, first-child, nth-child, not and form fields.