CSS :nth-child() Selector — Pattern-Based Element Selection

Master the CSS :nth-child() selector for pattern-based selection using An+B syntax. Create striped tables, grid layouts, and complex repeating patterns.

Pseudo-classes

Detailed Explanation

CSS :nth-child() Selector

The :nth-child() pseudo-class selects elements based on their position among siblings, using a formula-based pattern.

Syntax: An+B

The formula An+B defines the pattern:

  • A — cycle size (every A-th element)
  • B — offset (starting position)
  • n — counter starting from 0

Common Formulas

Selector Matches
:nth-child(odd) 1st, 3rd, 5th… (alias for 2n+1)
:nth-child(even) 2nd, 4th, 6th… (alias for 2n)
:nth-child(3) Only the 3rd child
:nth-child(3n) Every 3rd: 3, 6, 9…
:nth-child(3n+1) 1, 4, 7, 10…
:nth-child(-n+3) First 3 elements only
:nth-child(n+4) 4th element and beyond
:nth-child(n+2):nth-child(-n+5) Elements 2 through 5

Practical Examples

Striped table rows:

tr:nth-child(even) {
  background-color: #f5f5f5;
}

Grid masonry pattern:

.grid-item:nth-child(3n+1) { grid-column: 1; }
.grid-item:nth-child(3n+2) { grid-column: 2; }
.grid-item:nth-child(3n+3) { grid-column: 3; }

Limit visible items:

.item:nth-child(n+6) { display: none; }

:nth-child() vs :nth-of-type()

:nth-child() counts all siblings regardless of type, while :nth-of-type() counts only siblings of the same tag name. This distinction matters when elements of different types are mixed.

The of S Syntax (CSS Selectors Level 4)

/* Select the 2nd element among only the .active children */
:nth-child(2 of .active) { }

Use Case

The :nth-child() selector is ubiquitous in web development. It creates striped table rows for readability, implements grid layout patterns, limits the number of visible items in lists, creates rotating color schemes, handles spacing for the last item in lists, and powers responsive gallery layouts with different column arrangements.

Try It — CSS Selector Tester

Open full tool