Pseudo- classes in CSS: Concise and Resilient Selectors with :is()

The :is() pseudo-class is one of three logical pseudo-classes available in CSS—the other two being :not() and :where() (which we’ll discuss in the next sections).

You can use :is() to create more concise and resilient selectors. It’s a functional pseudo­class that accepts a selector list as its argument. Here’s an example:

article :is( hi, h2, h3, h4 ) {

font-family: ‘EB Garamond’, serif;

font-style: italic 45deg;

}

In this case, our selector matches <h1> , <h2> , <h3> , or <h4> elements that are the descendants of an <articLe> . It’s the equivalent of writing the following:

article h1,

article h2,

article h3,

article h4 {

font-family: ‘EB Garamond’, serif;

font-style: italic 45deg;

}

That’s a much longer selector list! Using :is() significantly reduces the length of selectors.

The :is() function accepts what’s known as a forgiving selector list. Consider the following CSS:

:is( :blank, :placeholder-shown ) {

font: inherit;

padding: 1rem;

color: #003a;

}

The selector above matches input elements that are blank or that have visible placeholder text. Here’s the catch: most browsers don’t yet support the :bLank pseudo-class. Despite this, our declarations will still be applied to elements that match :pLacehoLder-shown . A forgiving selector lists tells browsers to ignore selectors that the browser doesn’t understand.

Forgiving selector lists are a newer CSS concept. Earlier CSS specifications defined how a browser should treat a selector list that it can’t fully parse, whether the error is due to a lack of browser support or a typo. As explained in the CSS 2.1 specification:

CSS 2.1 gives a special meaning to the comma ( , ) in selectors. However, since it is not known if the comma may acquire other meanings in future updates of CSS, the whole statement should be ignored if there is an error anywhere in the selector, even though the rest of the selector may look reasonable in CSS 2.1.

In other words, if any item in a standard selector list isn’t supported, the browser ignores the entire rule. Using :is() , on the other hand, lets the browser ignore selectors that it doesn’t understand.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *