Using :is() to Condense Your CSS Rules

Content:

The pseudo element selector :is() is a great way to condense your complex CSS rules.

It allows multiple elements to be specified within a rule, combining individual selectors into one.

Consider the following code.

ul li,
ol li {
    color: blue;
}

This selector is targeting li elements inside either a ul, or ol element. Without using a preprocessor, there’s no way to simplify this selector.

That is, unless you use :is(). :is() allows the ul and ol selectors to be grouped together.

:is(ul, ol) li {
    color: blue;
}

The result of this is the same as the previous example, but takes one less line. I would also argue the meaning of the selector is clearer.

Its power becomes more obvious with more complex selectors.

article heading h1,
article heading h2,
article heading h3,
article heading h4,
article heading h5,
article heading h6,
article section h1,
article section h2,
article section h3,
article section h4,
article section h5,
article section h6 {
    color: blue;
}

Yuck. Here, we’re targeting all heading elements under either a heading or section tag, themselves under an article tag. Now if we rewrite this using :is()

article :is(heading, section) :is(h1, h2, h3, h4, h5, h6) {
    color: blue;
}

Much more compact. And again, I would argue this is much clearer than the previous code.

You can mix and match the selector types you want to target.

div :is(div, .container, #main-header)

It also ignores invalid selectors, unlike the standard way of writing CSS.

/* invalid */
div div,
div nope {}

/* valid */
div :is(div, nope) {}

:any() and :matches()

If you’ve ever used either the :any() or :matches() pseudo selectors, :is() might seem familiar.

:is() can be seen as the successor to :matches() (which itself was an update for :any()), and should be used in place of them. Browsers might still support these two, but it’s best to avoid them now :is() has become part of the CSS specification.

Browser Support

:is() is very well supported by the mainstream browsers, with Chrome, Safari, Firefox and Android Browser all having full support.

You can see the full browser support over at the Can I Use site.