A look at the CSS functional pseudo-class selector :is()

Written by
Published on
Category
CSS

If you are already familiar with the :matches() pseudo-class selector, then you are also familiar with :is(), and that's because :matches() has been renamed to :is().

And if you are not familiar with either, then read on, because :is() has alot going for it.

In the past, the only way to target multiple elements with the same style rules, was to essentially explicitly write out the entire rule for each case.

That meant that, if say, you wanted to style a <b> element inside of other elements, such as h1, h2, h3.. etc. then you would need to write out the given rule for each header element separated by a comma.

h1 > b, h2 > b, h3 > b, h3 > b{
    color: black;
}

Not really a big deal. But depending on the level of nesting and the overall complexity of the rule, you could end up with a rather long and difficult to edit CSS property in the end. Picture something like the following for example:

.item .title span, .item .content span, .item .footer span{

}

That's why the pseudo-class selector :is() is such a big deal. The above CSS header example could be rewritten as follows now:

:is(h1, h2, h3) > b{
    color: black;
}

Essentially, the :is() selector will match any of the given elements inside of the parenthesis. These can be simple things such as an h1 or an h2. Or they can be more complex nested rules.

Nesting :is()

Through the magic that is CSS, you can even nest multiple :is() selectors into a single rule.

.hero:is(h1,h2,:is(.header,.bold)) {
  font-weight: 900;
}

In this case, the innermost :is() selector would be applied first before the wrapping :is() selector.

Readability is overall improved and you also end up reducing the over CSS size as well. While you can use the :is() as a standalone rule, you can also apply it to other elements as well.

Say for example that you have an anchor tag <a> with :hover state and a 'selected' state once it has been clicked. You can target both of these cases with the following new style rule.

a:is(.selected, :hover){
    color: teal;
}

Overall, much less redundancy when specifying rules.

Browser compatibility

Currently, the :is() selector is supported in Chromium (>=88), Firefox (>= 78) and Safari (>=14).

On older browsers, you can use the :matches() selector to achieve the same functionality.

You can also use the :any() selector for older browsers given the appropriate vendor prefix, such as -webkit.

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

You can still use these older selectors to account for users on older browsers.

Comments

No messages posted yet

Developer Poll

Q:

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post