Day 35: forgiving selectors

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


There's a difference between listing selectors in :where(), :is(), and :has() and listing them in a regular selector list.

Let's say you have a button with the class .button and you apply the following styles.

.button:hover {
  background-color: hwb(100 0% 20%);
}
<button class="button">I'm a button</hover>

Nothing special, the color just changes on hover. If you add more and different selectors to this rule, it still works.

.button:hover,
.button:focus,
#btn {
  background-color: hwb(100 0% 20%);
}

Here's were it gets interesting: If one of the selectors in your list of selectors is invalid, the whole rule becomes invalid and declarations apply to none of the selectors.

.button:hover,
.button:focus,
$btn {
  background-color: hwb(200 20% 0%);
}

Even using a pseudo-class that doesn't exist or that isn't supported by the browser invalidates the whole rule.

.button:hover,
.button:focus,
.button:touch {
  background-color: hwb(200 20% 0%);
}

So, a downside to using a selector list is that a single invalid or unsupported selector in the list of selectors invalidates the entire rule.

That's different when you're using :has(), :where() or :is() because they're so-called “forgiving selectors”. They just ignore the invalid selectors and apply the rules to the others.

button:where(:hover, :focus, $btn) {
  background-color: hwb(90 20% 20%);
}
button:where(:hover, :focus, :touch) {
  background-color: hwb(52 10% 20%);
}

This means that another benefit of using :is() or :where(), besides less lines of code and more control over specificity, is that you can use selectors that don't work in every browser in a list of selectors without having to worry that they invalidate the whole rule.

See on CodePen

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS