CSS :nth-child(n of selector): Target Nth Matching Element
Select every nth matching element without counting others
:nth-child() counts all siblings by default, so mixed content breaks the expected pattern. The of selector syntax limits the count to only matching elements, giving reliable nth patterns regardless of what else is in the container.
.item:nth-child(2n) { background: var(--accent); }/* counts ALL siblings — breaks when non-.featured items are mixed in */// JS: items.forEach((el, i) => { if (el.classList.contains('featured') && i % 2 === 0) el.classList.add('nth-even') }); .item:nth-child(2n of .featured) { background: var(--accent);}/* counts only .featured items; other siblings don't affect the pattern */ nth child of Browser Support
This feature is well established and works across many devices and browser versions. It has been available across browsers since 2023.
Safe to use without fallbacks.
Counts only what matches
The count resets to only the elements matching the selector. Unrelated siblings are invisible to the counter.
No class injection
The old workaround was adding a class like .nth-2 via JavaScript. The of syntax removes that entirely.
Works with any An+B pattern
All the usual expressions apply: 2n, 3n+1, odd, even. Just scoped to the matching subset.
How it works
Plain :nth-child(2n) counts every child of the parent in document order, regardless of type or class. When items of different types are mixed together, the count includes all of them and the pattern lands on unpredictable elements.
The of selector syntax changes how the counter works. :nth-child(2n of .featured) first filters siblings to only those matching .featured, then applies the 2n pattern to that filtered set. Elements that don't match the selector don't affect the count at all.
The selector inside of can be any valid CSS selector, including compound selectors and pseudo-classes. You can also combine it with an outer selector: li:nth-child(3n of li.card) selects every third li.card without being affected by other li elements in the list.