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

SyntaxWhat it does
oddodd: 1, 3, 5, … (same as 2n+1)
eveneven: 2, 4, 6, … (same as 2n)
3the third only
3nevery third: 3, 6, 9, …
3n+11, 4, 7, …
n+4from the fourth on
-n+3the first three
2 of .itemthe 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

▶ Open in HTML Editor

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

See also