Published at
Updated at
Reading time

Just parking this CSS snippet on my blog for my future self. ๐Ÿ™ˆ

If you want to select elements only when there's a given number of them, you can use a :nth-last-child() selector combination.

The following selector combination is called a "quantity query".

li:nth-last-child(3) ~ li {
  color: red;

And it selects all list elements when there are at least three of them. See it in action below. ๐Ÿ‘‡


The CSS selector is hard to read but works. ๐Ÿซฃ

Update: :has() enables easier-to-read quantity queries

The quantity query above is based on some selector trickery and definitely hard to remember. Luckily, the new :has() pseudo-class is on its way to cross-browser support to simplify such monstrosities!

MDN Compat Data (source)
Browser support info for :has()

With :has() the quantity query becomes a resonable one-liner that reads as "Select all li elements in a list that includes a third last child counting from the end."


Boom! And that's all it takes to select elements from a list with at least three items. ๐ŸŽ‰

And even exact matches are possible by selecting "all list elements in a list including a list element which is the third and last child."


:has() is a gift that keeps giving!

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 8 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles