CSS nth selectors
A visual playground for :nth-child, :nth-of-type and friends, plus the sibling combinators.
Playground
1
2
345
6
7
89
10
111213
14
15
1617
18
192021
22
2324
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.
| Formula | Matches |
|---|---|
3 | Only the 3rd |
odd | 1, 3, 5, …, same as 2n+1 |
even | 2, 4, 6, …, same as 2n |
3n | 3, 6, 9, … |
3n+1 | 1, 4, 7, … |
3n-1 | 2, 5, 8, … |
n+4 | The 4th and everything after it |
-n+3 | The 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().