CSS nth-child Tester
Note: n counts from zero, which is why 3n+2 matches positions 2, 5 and 8. Read b as an offset applied from the very first iteration, not as the position to start counting from.
Negative values are where it gets useful. -n+3 selects the first three: at n=0 it is 3, at n=1 it is 2, at n=2 it is 1, and after that the result goes non-positive and stops matching. n+4 does the opposite and selects everything from the fourth onwards. Neither has an obvious name, and both are worth remembering, because between them they cover most of the real cases that are not simply odd or even.
The distinction that causes the most confusion is nth-child versus nth-of-type. nth-child counts every sibling regardless of what it is, then checks whether the one at that position matches your selector. nth-of-type counts only elements of that type. So p:nth-child(2) matches a paragraph only if it is literally the second child β if a heading comes first, it will not match at all β while p:nth-of-type(2) finds the second paragraph regardless of what else is interleaved. When a selector that looks obviously correct matches nothing, this is usually why.
The modern of S syntax is included too, since it is now widely supported and finally allows counting only among elements matching a selector.
Frequently Asked Questions
Why does my nth-child selector match nothing?
Most often because nth-child counts all siblings, not just the ones matching your selector. p:nth-child(2) means 'the second child, and it must be a paragraph' β so a heading in first position breaks it. Use nth-of-type when you want the second paragraph regardless of what else is there.
How do I select the first three items?
With :nth-child(-n+3). Because n counts from zero, the result descends 3, 2, 1 and then stops being positive, which is exactly the first three. For everything from the fourth onwards, use :nth-child(n+4).
Does n start at zero or one?
Zero. That is why 3n+2 matches positions 2, 5 and 8 rather than 2, 5, 8 starting from the third. Read the b value as an offset applied from the very first iteration, not as a starting position.
What does the of S syntax do?
:nth-child(2 of .featured) counts only among elements with that class, which nth-child could never do on its own β it finds the second featured item even if unfeatured ones sit between them. It is supported in all current browsers but has no fallback in older ones.
Can I use this to zebra-stripe a table?
Yes, and tbody tr:nth-child(odd) is the right form. Applying it to tr alone can include rows in thead and tfoot, which shifts the alternation and colours a header you did not mean to touch.

