Make repetitive CSS compact using :is() pseudo-class function

Amit Merchant · July 5, 2020 ·

The CSS has many experimental features, that if used cautiously, can be proven very handy in simplifying things.

For instance, the :is() CSS pseudo-class function. What this function does is it takes a selector list as its argument and selects any element that can be selected by one of the selectors in that list. This is useful for writing large selectors in a more compact form.

So, if you’ve following CSS at hand…

header p:hover,
main p:hover,
footer p:hover {
  color: red;
  cursor: pointer;
}

Here, p:hover is “common” across all three selectors. The :is() function can be used to shorten this to the following.

:is(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

As you can see, it looks more concise and refactorable now.

But as I said, this function is an experimental one. So, not every browser has support for the same. So, to mitigate this you can use fallback functions for the same like *-any() or :matches().

:-webkit-any(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}
:-moz-any(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}
:matches(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

Here is the list of all browsers that supports :is() currently.

Data on support for the css-matches-pseudo feature across the major browsers from caniuse.com

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!