The :nth-child() pseudo-class
:nth-child() selects elements by their position among siblings: every second table row, the first three list items, every third card.
Syntax
:nth-child(odd)
:nth-child(even)
:nth-child(3)
:nth-child(an + b) /* n = 0, 1, 2, … */ Formula examples
| Syntax | What it does |
|---|---|
odd | odd: 1, 3, 5, … (same as 2n+1) |
even | even: 2, 4, 6, … (same as 2n) |
3 | the third only |
3n | every third: 3, 6, 9, … |
3n+1 | 1, 4, 7, … |
n+4 | from the fourth on |
-n+3 | the first three |
2 of .item | the second among elements with class .item (Selectors 4, modern browsers) |
Example
li { padding: 4px 8px; }
li:nth-child(odd) { background: #e0f2fe; }
li:nth-child(-n+3) { font-weight: bold; }
li:nth-child(3n) { color: #dc2626; } <ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
</ul> Result
Good to know
- Counting starts at 1, while n in the formula runs 0, 1, 2, … That is why -n+3 gives 3, 2, 1 — the first three elements.
- :nth-child counts all siblings of any tag: p:nth-child(2) matches only if the p is the second of all children. To count only p elements, use :nth-of-type().
- Related pseudo-classes: :first-child, :last-child and :nth-last-child(), which counts from the end.
Sources and specification
- MDN: :nth-child() — MDN Web Docs
- Selectors Level 4 (W3C) — W3C
See also
CSS selectors
CSS selectors pick elements to style: by tag, class, id, attribute and state, plus combinators and specificity — with examples for beginners.
The <li> tag
The value attribute of <li> inside an ordered list.
The <table> tag
Table structure: thead, tbody, tr, th, td. Example and practical notes.
Responsive table
An overflow-x:auto wrapper for horizontal table scrolling on narrow screens.