Skip to content

CSS Selectors

Position nth-child(n) with limit

About

The :nth-child() pseudo-class supports a counter variable n which starts at 0 and increments by 1 for every element. It allows you limit the number of elements being matched.

First 5 elements

The selector :nth-child(-n + 5)matches the first 5 elements.

  • n = 0 → (-n + 5) = (-0 + 5) = 5
  • n = 1 → (-n + 5) = (-1 + 5) = 4
  • n = 2 → (-n + 5) = (-2 + 5) = 3
  • n = 3 → (-n + 5) = (-3 + 5) = 2
  • n = 4 → (-n + 5) = (-4 + 5) = 1
  • n = 5 → (-n + 5) = (-5 + 5) = 0 (no match because the first element starts with 1)