Back to Playground

CSS nth selectors

A visual playground for :nth-child, :nth-of-type and friends, plus the sibling combinators.

Playground

1
2
34
5
6
7
8
9
10
1112
13
14
15
16
17
18
1920
21
22
23
24

Squares are <div>, circles are <span>. The number is the position among all siblings.

How An+B works

n is a counter that starts at 0 and goes up by one. The browser fills in every value and selects each element whose position comes out of the formula.A is the step size, B the offset. Positions start at 1, so anything that comes out at 0 or below matches nothing.

FormulaMatches
3Only the 3rd
odd1, 3, 5, …, same as 2n+1
even2, 4, 6, …, same as 2n
3n3, 6, 9, …
3n+11, 4, 7, …
3n-12, 5, 8, …
n+4The 4th and everything after it
-n+3The first 3

The variants

:nth-child()
Counts every sibling, no matter the element type.
:nth-last-child()
Same as nth-child, but counts from the last sibling backwards.
:nth-of-type()
Only counts siblings with the same tag name as the element itself.
:nth-last-of-type()
Same as nth-of-type, counting from the end.
:nth-child(An+B of S)
Filters the siblings by selector S first, then counts. Like nth-of-type, but for any selector, such as :nth-child(odd of .visible).

Watch out, p:nth-child(2) is not the second paragraph. It is the second child, but only if that child happens to be a p. Usep:nth-of-type(2) for the second paragraph.

Shorthands

:first-child
:nth-child(1)
:last-child
:nth-last-child(1)
:only-child
:first-child:last-child
:first-of-type
:nth-of-type(1)
:last-of-type
:nth-last-of-type(1)
:only-of-type
:first-of-type:last-of-type

Bonus: sibling combinators

Pick an element to be A and a combinator, and see which Bsiblings get selected. Siblings only look forward, so going backwards takes:has().

Combinator