The :is() CSS pseudo-class function

Learn how to use the :is() CSS pseudo-class function to reduce the complexity and verboseness of your CSS selectors.
January 30, 2023CSS
2 min read

We can use the :is() CSS pseudo-class function to select any elements using a list of CSS selectors. This function helps us to write verbose and complex CSS selectors in a more elegant way.

Multiple CSS pseudo-classes

Let's take a look at an example of how the :is() pseudo-class function makes it easier to define CSS rules for the various states of a HTML link. The various states consist of the following CSS pseudo-classes: :visited, :hover, and :active.

link.html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>My Link</title>
</head>
  <body>
    <a href="/" class="Link">My Link</a>
  </body>
</html>
link.css
.Link:visited,
.Link:hover,
.Link:active {
  color: red;
}

We can re-write the CSS for this example using the :is() pseudo-class function.

link.css
.Link:is(:visited, :hover, :active) {
  color: red;
}

The :is() pseudo-class function allows us to condense three CSS rules into one rule. We are able to achieve the same result with less characters. Not only is it quicker to write, but it results in a more performant site because there's less code that will be bundled and shipped to the browser.

Multiple CSS classes

We can also use the :is() pseudo-class function for multiple CSS classes.

Let's take a look at an example that consists of two links that are assigned separate classes.

links.html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>My Links</title>
</head>
  <body>
    <a href="/" class="LinkOne">My Link One</a>
    <a href="/" class="LinkTwo">My Link Two</a>
  </body>
</html>

We can apply CSS styling for both classes.

links.css
:is(.LinkOne, .LinkTwo) {
  color: red;
}

This will always make both links appear in red. However, we can customize the styling by targeting the pseudo-classes that apply to each class.

links.css
.LinkOne:is(:visited, :hover, :active),
.LinkTwo:is(:visited, :hover, :active) {
  color: red;
}

Now, both links only appear in red when they are visited, hovered over, or in an active state.

We can simplify the CSS rules that we defined by chaining the :is() pseudo-class function. This helps us reduce the amount of code that is needed.

links.css
:is(.LinkOne, .LinkTwo):is(:visited, :hover, :active) {
  color: red;
}

Conclusion

Reduce the complexity and verboseness of your CSS selectors by using the :is() pseudo-class function.

It looks like something we would find in a CSS preprocessor, like Sass, but it's native to CSS. It's supported in all modern web browsers.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.