Episode 22 of 53

Nth Child Selector

Learn the powerful :nth-child() selector for pattern-based element targeting.

The :nth-child() pseudo-class lets you select elements based on their position using a formula.

Basic Usage

/* Select the 3rd child */
li:nth-child(3) { color: red; }

/* Select even children */
li:nth-child(even) { background: #f5f5f5; }

/* Select odd children */
li:nth-child(odd) { background: #fff; }

The Formula: an + b

The real power of :nth-child() comes from the an + b formula:

  • a — the cycle size (repeating pattern)
  • n — a counter starting from 0
  • b — the offset (starting position)
/* Every 3rd element: 3, 6, 9, 12... */
li:nth-child(3n) { color: blue; }

/* Every 3rd, starting from 2nd: 2, 5, 8, 11... */
li:nth-child(3n+2) { color: green; }

/* First 5 elements */
li:nth-child(-n+5) { font-weight: bold; }

Zebra Striping a Table

/* Classic alternating row colors */
tr:nth-child(even) {
    background-color: #f8f9fa;
}

tr:nth-child(odd) {
    background-color: #fff;
}

Common Patterns

  • :nth-child(2n) — every even element (same as even)
  • :nth-child(2n+1) — every odd element (same as odd)
  • :nth-child(n+6) — from the 6th element onwards
  • :nth-child(-n+3) — only the first 3 elements