Codectionary / Developer documentation / CSS

Structural Pseudo-classes: nth-child()

Structural pseudo-classes select elements based on their position among siblings, without needing extra classes. :first-child and :last-child match the first/last element. :nth-child() accepts a formula (like 2n for even, 2n+1 for odd) or a simple number, letting you target patterns like every third item or striped table rows.

Syntax

:first-child, :last-child, :nth-child(formula)

Examples

first-child, last-child, and a Specific Position

Targeting elements by their fixed position among siblings.

li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(3) { color: red; } /* the exact third item */

nth-child() Formulas for Patterns

Striped rows and other repeating patterns using the an+b formula.

tr:nth-child(even) { background: #f9fafb; }  /* zebra striping */
tr:nth-child(odd) { background: white; }

li:nth-child(3n) { margin-right: 0; } /* every 3rd item, e.g. for a 3-column grid */
li:nth-child(n + 4) { display: none; } /* hide everything from the 4th item onward */

Parameters and values

  • :first-child / :last-child (pseudo-class): Matches if the element is the first/last among its siblings
  • :nth-child(n) (pseudo-class): Matches based on a formula or specific position among siblings
  • :nth-of-type(n) (pseudo-class): Like nth-child, but only counts siblings of the same element type
  • :only-child (pseudo-class): Matches an element with no siblings at all

Best practices

  • Use :nth-child(even)/:nth-child(odd) for striped table rows or lists instead of manually adding alternating classes
  • Use :nth-of-type() instead of :nth-child() when other, different element types are mixed in among the siblings you are targeting
  • Combine :nth-child() with the general an+b formula for advanced patterns, like hiding all items after a certain position for a "show more" pattern
  • Remember these pseudo-classes count ALL sibling elements, not just ones matching your selector, unless you specifically use the :of-type variants

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation