🎨 Fix a :nth-child Selector Miscounting After a Hidden Sibling
The :nth-child() selector counts every element sibling in the DOM in document order, completely independent of whether display: none is hiding some of them visually. A list where every third item gets a different background, built against :nth-child(3n), will count a hidden filtered-out item exactly the same as a visible one — so as soon as a filtering script hides a few items with CSS instead of removing them from the DOM, the striping pattern visibly shifts out of sync with what’s actually on screen, because the selector was never told to skip what it can’t see.
🔎 The Problem
.list-item:nth-child(3n) {
background: #f1f5f9;
}
/* Items 1,2,3(hidden via JS),4,5,6... still counts the hidden item 3
as child #3 - so visible items 2 and 4 end up looking like neighbors
that should both be striped or both plain, but only one of them is,
because the selector's count never skipped the display:none item */
✅ Fix: A :nth-child Selector Miscounting After a Hidden Sibling
- Use the :nth-child(An+B of S) syntax where supported (Chromium and Firefox both support it) to count only elements matching a selector, such as :nth-child(3n of :not(.hidden)), so hidden items drop out of the count entirely.
- Where that syntax isn’t available in your minimum supported browser, remove filtered-out items from the DOM instead of hiding them with CSS, so :nth-child counts only what’s actually meant to be there.
- As a fallback, apply the striping with a small script that re-numbers visible items directly (a data-index attribute updated on filter) rather than depending on CSS structural counting at all.
🚨 Why This Is Dangerous
- A striping or spacing rule that silently desyncs from what’s visible is easy to dismiss as “a minor visual glitch” when it’s really a sign that your selector and your filtering logic disagree about what counts as an item.
nth-child counts the DOM, not the screen — display: none never told it to look away.




