Web Advent Calendar 2024

nth-child selector with filter

You probably know the nth-child() CSS selector. It matches for elements, that are the nth child of their parent.

<!-- having a parent with several children -->
<p class="list1"> <span>One</span> <span>Two</span> <span>Three</span> <span>Four</span> <span>Five</span> <span>Six</span> <span>Seven</span> </p>
.list1 span:nth-child(3) { font-weight: bold; }

One Two Three Four Five Six Seven

But there is a lesser-known cool feature.

The nth-child selector also supports a filter selector, that lets you select the nth child matching that selector:

<!-- having a parent with several children of different classes -->
<p class="list2"> <span class="odd">One</span> <span class="even">Two</span> <span class="odd">Three</span> <span class="even">Four</span> <span class="odd">Five</span> <span class="even">Six</span> <span class="odd">Seven</span> </p>
.list2 :nth-child(2 of .even) { font-weight: bold; }

One Two Three Four Five Six Seven

Bonus party trick: You can target lists that have exactly n children, by combining the nth-child and last-child selectors.

.list3:has(span:nth-child(4):last-child) { font-weight: bold; }

One Two Three

One Two Three Four

One Two Three Four Five