The CSS quantity query with :nth-last-child()
- 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. ๐
HTML
CSS
The CSS selector is hard to read but works. ๐ซฃ
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!
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."
HTML
CSS
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."
HTML
CSS
:has()
is a gift that keeps giving!
Join 5.5k readers and learn something new every week with Web Weekly.