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.

Old way JS required
.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') });
Modern
1 selector
.item:nth-child(2n of .featured)   {  background: var(--accent);}/* counts only .featured items; other siblings don't affect the pattern */
Widely available Since 2023 90% global usage

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.

111+
113+
9+
111+
Every 2nd .featured card highlighted, regardless of other siblings

:nth-child(2n) — counts all

Other
Other

Highlights 2nd and 4th child overall, not 2nd featured

:nth-child(2n of .featured) — counts only .featured

Other
Other

Highlights every 2nd .featured: B and D

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.

Old Approach
JS class injection
Add .nth-X classes manually
Modern Approach
:nth-child(n of S)
Pure CSS
Baseline
Widely available
Since 2023

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.

ESC