Shorten Your CSS Selectors With The :is Pseudo-Class

natclark

Nathan

Posted on September 10, 2021

Shorten Your CSS Selectors With The :is Pseudo-Class

One CSS feature I wish I knew about long before I discovered it is the :is pseudo-class.

You can use it to shorten some of your longer selectors.

For example, consider the following declaration block:

h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

Seems a bit repetitive, right?

Now, here's how our code would expand if we wanted to add a class to each <a> tag:

h1 a.class, h2 a.class, h3 a.class, h4 a.class, h5 a.class, h5 a.class {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

We'd have to re-type ".class" six times.

And this is just one small example of how the :is selector can save you some keystrokes:

:is(h1, h2, h3, h4, h5, h6) a {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

In this case, if we wanted to add that same class from earlier, we'd just have to type it once, instead of six times:

:is(h1, h2, h3, h4, h5, h6) a.class {
    /* some styles would go here */
}
Enter fullscreen mode Exit fullscreen mode

So basically, all it does is iterate over each comma-separated internal selector and apply it to the sibling or child selector.

Performance implications

One important thing to remember about CSS is that subtle differences in selector syntax can carry exponential impact on performance.

For example, "div > p" is far less performant than "div p", because browers interpret selectors from right to left. While this is something I might write about more in the future, it's beyond the scope of this post.

So as far as the :is selector goes, I just want to note that pseudo-classes (including :is) are the most inefficient selector type.

Also, the browser compatibility could be improved. I'd strongly suggest looking into some backwards-compatible pseudo-classes with the same functionality, such as ":matches()".

Conclusion

I hope you enjoyed this article, and I hope it saves you some time in the future!

Besides, who wants to sit around and rewrite each selector six times every time there's a small change?

πŸ’– πŸ’ͺ πŸ™… 🚩
natclark
Nathan

Posted on September 10, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related