Skip to main content Accessibility Feedback

How to apply CSS only if there are a certain number of nested elements

This week, I had to write CSS for a design where a list of elements got a bit of extra design treatment if there were at least three nested items inside it.

<!-- Base design -->
<ul class="magic-list">
	<li>Item 1</li>
	<li>Item 2</li>
</ul>

<!-- Extra design -->
<ul class="magic-list">
	<li>Item 1</li>
	<li>Item 2</li>
	<li>Item 3</li>
	<li>Item 4</li>
	<!-- ... -->
</ul>

I really wanted to avoid using JavaScript to add/remove an extra class, and the the :has() pseudo-class and the nth-* pseudo-class made it shockingly easy!

.magic-list:has(> :nth-of-type(3)) {
	/* extra styles... */
}

This checks if the .magic-list has a direct descendant in the third spot. If so, it applies the styles. If not, it skips them. This works for any number of nested items above three.

Modern CSS is magic!