CSS Quantity Queries

— 16.02.2017

Hi,

today I want to talk about a handy CSS snippet for day to day usage. The CSS Quantity Queries!

How to use?

I don’t want to give you the full background or insight into those. Especially as Heidon Pickering has done this already in a great A List Apart article.

Let’s say you have an unordered list

<ul>
	<li>1st</li>
	<li>2nd</li>
	<li>3rd</li>
</ul>

you want or need to style somehow different depending on the quantity of list items in it. Here come the quantity queries into the game.

li:nth-last-child(3):first-child, 
li:nth-last-child(3):first-child ~ li {
	color: green;
}

Explanation

I admit that those queries are not the prettiest looking things on earth, but they work as expected. The first selector gives us the li which is the 3rd one by start counting from the last li child of the list and the first child likewise — aka. the first li of a list with three elements — tada! This is apparently the magic behind.

The second selector is only to select all upcoming li after the first one, to adapt the CSS rules in the end for all elements in the list.

So the above code snippet will style all list items of a list with three entries in green color.

Advanced Usage - Quantity Thresholds

Obviously you may asking for a more realistic use case than styling for a discrete quantity, but styling differently starting with a given threshold like “three or more entries”.

Here we can use the n argument:

li:nth-last-child(n+3), 
li:nth-last-child(n+3) ~ li {
	color: green;
}

where li:nth-last-child(n+3) “[…] omits the last [two] items from a set of any length, meaning that when you reduce the length of the set below [three], you cease to see any selected items. It’s a sort of “sliding doors” effect. […] If, indeed, the set is greater than or equal to [three] in total, then all that remains is to style those last five items as well.” (A List Apart article “Quantity Queries for CSS”).

Here you can play around with a live CodePen demo. Have fun!

Happy usage!