Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

:nth-child()

Matches children by their position: the third, every even one, every third one.

Syntax

selector:nth-child(an+b) { … }

Parameters

ParameterTypeDescription
nnumberA position counted from 1: `:nth-child(3)`.
odd | evenkeywordOdd or even positions.
an+bformulaA 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.

Thanks for reading!

Donate to the site — we work hard for you.