🎨 The nth-child That Counted the Wrong Crowd
:nth-child(n) counts a position among ALL of an element’s siblings, regardless of what selector it’s attached to – li:nth-child(2) doesn’t mean ‘the second li,’ it means ‘this element, if it happens to be an li, counted by its position among every sibling of any kind.’ Mix list items with a non-li element (a divider, a heading, an ad slot) anywhere in between, and the count shifts for every item after it, picking out the wrong element entirely while compiling and rendering with zero errors.
🔎 The Problem
<ul>
<li>Item A</li>
<li class="divider"></li> <!-- not styled with nth-child -->
<li>Item B</li>
<li>Item C</li>
</ul>
<style>
/* Intent: highlight the second REAL item (Item B). */
li:nth-child(2) { background: yellow; }
</style>
<!-- What actually gets highlighted: the divider, which IS
the second <li> child by raw position - "Item B" is
the third child overall, so nth-child(2) never
selects it, even though visually it's "the second
real item" to a person reading the list. -->
âś… Fix: Use :nth-of-type, or the of S Selector-List Syntax for a Filtered Count
- If every sibling in the group is the same tag (all <li>, mixed only with non-element content),
:nth-of-type(n)counts by tag name among siblings of that same tag – closer to what most people expect:nth-childto do, but still not a filter by class. - For counting by an actual CSS selector – ‘the 2nd li that doesn’t have class divider’ – use the newer
:nth-child(2 of li:not(.divider))selector-list syntax where it’s supported; it’s the direct, purpose-built way to count only the siblings matching an arbitrary selector. - Where broad support for the
of Ssyntax isn’t an option yet, the dependable fallback is giving the excluded elements (dividers, ads, headings) a wrapper or a different parent entirely, so the list you’re counting through only ever contains the items you actually mean to count.
⚠️ Why This Is Easy to Miss
- The selector is valid, specific, and clearly matches something – there’s no error, no unmatched-selector warning, just a highlight landing on an element that isn’t the one anyone was picturing when they wrote ‘2nd item.’
- It only breaks the moment a non-uniform sibling gets inserted into a previously uniform list – a design built and tested against a clean list of identical items can ship fine, then quietly mis-target the moment a divider or an ad slot gets added later.
:nth-child doesn’t know what selector it’s attached to when it’s counting – it’s already decided which child is ‘the second one’ before it ever checks whether that child matches anything you wrote.
