:is() Pseudo-Class

In CSS the :is() selector is a pseudo-class function, as you can see () in the end. The :is() pseudo-class selector takes a list of the selector as its argument. It allows us to write long and complex statements more compactly. So in this article, we are going to explain :is() pseudo-class with examples.

I. Why use :is pseudo-class?

While writing compound selectors, it sometimes turns into a complex one. And with these complex selectors, we need to be more careful.

header h1, header a, header p, header .btn, header .card {

color: red; 

} 

The above code is very lengthy, and it can be annoying if we want to make a change here.

So instead of writing a whole bunch of selectors, you could use :is(). It makes your code look cleaner and increases its legibility. Also, with :is(), we need to change only one selector instead of many.

header :is(h1, a, p, .btn, .card){

color: red;

}

We are just putting the parent selector once, and then we are passing the list of selectors in the argument. The :is() pseudo-class increases the legibility of your code. Also, with :is(), we need to change only one selector instead of many.

II. Invalid Selectors

If you put an invalid selector like :a in the big chain of selectors, the browser will ignore the whole chain of selectors and throw your entire block into the garbage.

header h1, header :a, header :p {

color: red; //the color of the h1 heading will not change to red.

} 

But when using :is() pseudo-class, instead of ignoring the whole list of selectors, the browser will only skip the incorrect or invalid one, and the rest will work fine.

header :is(h1, :a, :p){

color: red; //the color of the h1 heading will change to red.

}

III. Specificity of :is()

According to W3C Working Draft:

The specificity of the :is() pseudo-class is replaced by the specificity of its most specific argument. Thus, a selector is written with :is() does not necessarily have equivalent specificity to the equivalent selector written without :is().

That means the specificity of :is() is automatically set to the most specific items in the argument list.

To understand the above statement entirely, let’s take an example.

header :is(h1, .list) // This has the higher preference

//then this, even if it comes later

header h1{........}

The :is() has a higher preference because of its heavier selector, which is .list. Also, if .list is not there in the argument list, then the preferences of the normal selector and the :is() will remain the same.

Hopefully, the above write-up was enough for you to understand :is pseudo-class entirely. If you have any questions or suggestions, you can write to us in the comment section below.

Happy Coding!

Some links on this page are affiliate links. This means that if you choose to make a purchase, we may earn a small commission at no extra cost to you. For more information, Go here

Leave a Reply

Your email address will not be published. Required fields are marked *