Published at
Updated at
Reading time
2min

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(n+3),
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. ๐Ÿ‘‡

Preview

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()
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
105105105103*10315.415.420.0105

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."

Preview

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."

Preview

: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 12 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.