DEV Community

Nic
Nic

Posted on • Originally published at blog.nicm42.co.uk on

A use case for :is

I've known that :is and :where have existed for a while. But I hadn't seen a reason to change my autopilot of comma separation. Until recently.

I had a situation where I really wanted to use :has. But it's not quite ready for production code yet (it's not in Firefox at all, which is my favourite browser). The easy solution was to use JavaScript to add a class, which I could use instead of :has. But I thought I'd do some future-proofing and use :has anyway, so if someone has no JavaScript in their browser, but with a new enough browser where :has works, the styling I needed to do would work for them.

So that was fine and I ended up with this bit of CSS:

div:has(img),
div.has-image {
  /* styling goes here */
}
Enter fullscreen mode Exit fullscreen mode

This worked fine in Chrome, but Firefox ignored all of that styling. That's because it didn't understand the first line, so it ignored the whole thing.

But :is works because if it doesn't understand something, it only ignores the bit it doesn't understand. So changing the code to this made it work in Firefox:

div:is(:has(img),has-image) {
  /* styling goes here */
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)