where is not is
I've never fully understood the difference between the :where
and :is
CSS selectors so, in the spirit of a random article I read online, I'm sharing my discovery here.
:is
allows you to represent an or-condition: :is(.class, #id) *
selects all elements that are children of .class
or #id
.
:where
allows you to represent an or-condition: :where(.class, #id) *
selects all elements that are children of .class
or #id
.
The difference lies in the specificity: :is
inherits the specificity of the selected match, whereas :where
always has a specificity of 0.
As such, my default is :is
since it more closely follows my expectations of the cascade.
One day I'll encounter a special case where :where
is needed and will update this post to include it.
~~~
It's almost a year later and I've finally used :where
!
I was working on my notes app and ran into an issue where I wanted to style <a>
tags within a few elements specified by IDs, but then use the same :focus-visible
for all elements on the page.
This code meant the ID selector was more specific than the pseudo-class:
:is(#id0, #id1) > a { background: white; }
:focus-visible { background: black; }
But using :where
reduced the specifity enough for the pseudo-class to take control:
:where(#id0, #id1) > a { background: white; }
:focus-visible { background: black; }
This isn't a problem one should encounter in industry since styling by ID is often problematic but, when making a tiny website where ID collisions are unlikely, it works fantastically.