Selection by Position

These pseudo-classes allow selecting elements based on their ordinal number within a parent.

1. Basic: :first-child and :last-child

Select the very first or very last child.

  • Why: Remove margin from last paragraph or make first menu item bold.

2. Flexible: :nth-child(n)

Most powerful tool. In parentheses you can use:

  • Number: :nth-child(3) — strictly the third.
  • Keywords: odd (odd), even (even).
  • Formula An + B:
    • 3n — every third (3, 6, 9...).
    • 2n + 1 — every second, starting from first (1, 3, 5...).
    • n + 5 — all elements starting from fifth.

3. Important Difference: :nth-child vs :nth-of-type

  • :nth-child: Counts absolutely all " siblings " (both div, p, and span). If the third child is an image and your selector is p:nth-child(3), it won't select anything.
  • :nth-of-type: Counts only elements of the specified type! p:nth-of-type(3) will reliably select the third paragraph, even if other tags lie between them.
Tip

Use :nth-of-type if your markup is heterogeneous and contains different tag types in a row.