Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to select the least number of elements in CSS

There’s always a talk going on about how we can incorporate conditions in CSS and recently, I found an interesting scenario in one of the tweets by Stefan Judis that shows how we can combine different selectors and operators to sort of sprinkle the magic of conditions in CSS.

The scenario is something like this. We have a set of elements, let’s say <li>, that need to be styled only when a minimum number of the element exists.

For instance, we want to set the color of all the <li>s to red when there are at least three <li> exists.

Here’s how we can do it.

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

As you can tell, we are using nth-last-child and ~(General sibling combinator) to achieve this.

The li:nth-last-child(n+3) would select the first <li> and li:nth-last-child(3) ~ li would select the next two adjoining <li>s with the help of ~(General sibling combinator).

Together, the statements will form a condition that would style the <li>s only if there are at least three of them exists.

Here’s everything put together.

See the Pen Select Least Items using CSS by Amit Merchant (@amit_merchant) on CodePen.

Try removing one of the <li> in the example to see the condition in action.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.