Search code examples
csscss-selectorspseudo-class

Can we achieve anything with the new CSS :is() pseudo-class that we can't already achieve with comma-separated queries?


I've been reading up on the new pseudo-classes in CSS Selectors Level 4.

The pseudo-class :is() immediately caught my eye, but after an all-too-brief moment of enthusiasm... I was suddenly uncertain if it introduced any new capability at all.

In A Guide To Newly Supported, Modern CSS Pseudo-Class Selectors, Stephanie Eckles introduces several use cases, including:

  • :is(-ua-invalid, article, p)
  • :is(#id, p)
  • :is(p, a)
  • :is(h1, h2, h3)
  • :is(h2, h3):not(:first-child)
  • p:is(article > *)

Looks great, but... aren't these just aliases for:

  • -ua-invalid, article, p
  • #id, p
  • p, a
  • h1, h2, h3
  • h2:not(:first-child), h3:not(:first-child)
  • article > p

Apart from the fifth bullet above, the comma-separated lists of selectors are actually shorter (and, possibly, more efficient) than the :is() pseudo-class syntax... mostly because the :is() function is simply employed to enclose that list (which already represents valid syntax) in parens.

Have I missed something? Are there cleverer things you can do with :is() that leave comma-separated lists of CSS selectors behind?


Solution

  • You are actually dealing with basic examples but consider more complex ones like the following:

    .box h1, .box h2, .box h3, .box h4
    

    In order to avoid repeating the .box we use

    .box :is(h1, h2, h3, h4)
    

    As far as I know, this was the main motivation for :is(): avoid rule duplication.

    Another common example is the table selectors:

    table tr td, table tr th
    

    now will become

    table tr :is(td, th)