CSS - Pseudo-class :is()



The CSS pseudo-class function :is() takes the arguments as a list of selectors, and thus targets any element that can be selected by any of the selectors in the list.

The pseudo-class :is():

  • Simplifies large number of selectors that are required to be written, in a more compact form.

  • Simplifies the section selectors i.e while dealing with HTML sections and headings at different levels, such as <section>, <article>, <aside>, and <nav>.

  • Does not select pseudo-elements. Refer the syntax below, these are not allowed:

    sample-element:is(::before, ::after) {
       display: block;
    }
    
    :is(sample-element::before, sample-element::after) {
       display: block;
    }
    

This pseudo-class was originally called :matches (and :any()).

The pseudo-elements are not valid as a value in the selector list for :is() pseudo-class.

:is() vs :where()

:is() is responsible for counting towards more specific of all the selectors in the list, whereas :where() holds the specificity value of 0.

Forgiving selector parsing

  • With usage of :is() and :where(), when one of the selectors fail to parse, instead of the whole list of selectors being deemed invalid, only the incorrect or unsupported selectors gets ignored and the rest of the selectors are used.

  • :is(:valid, :unsupported) − this will parse correctly and match :valid, even when the browsers don't support :unsupported.

Syntax

:is(<forgiving-selector-list>) {
   /* ... */
}

CSS :is Example

Following example demonstrates use of :is() function pseudo-class. Here, :is() pseudo-class function is applied on h1, h2, h3 and a elements. So wherever these elements are found, the appropriate styles are applied:

<html>
<head>
<style>
   body {
      font: 300 90%/1.4 system-ui;
      margin: 1rem;
   }
   main :is(h1, h2, h3) {
      color: green;
   }
   main :is(a) {
      color: red;
      font-size: large;
   }
</style>
</head>
<body>
   <main>
      <h1>:is() pseudo-class example</h1>
      <h3>Li Europan lingues</h3>
      <a href="">es membres del sam familie</a>. <p>Lor separat existentie es un myth.</p>
      <h2>Por scientie, musica, sport etc, litot Europa usa li sam vocabular.</h2>
      <p>Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.</p>
      <p>At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>
      <h3>Ma quande lingues coalesce</h3>
      <p>li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues.</p>
      <p>It va esser tam simplic quam <a href="">Occidental</a> in fact, it va esser Occidental.</p>
   </main>
</body>
</html>
Advertisements