🔍 :is() and :where()
·3 min read
Both selectors (
:where()) have been around for some time and are compatible with most modern browsers. These are very useful selectors, which allow us to simplify complex and repeated CSS selectors. Both take as arguments a list of selectors; they can select any element that can be selected by one of the selectors in this list.
Pretty simple right? 🤔 However, because it is relatively new, many people still don't know about them or don't know how to apply them in their projects. So I want this article to give examples of how to use it and show the difference between them.
👇🏻 Below is the traditional way of selecting an item from a list:
✅ Now see how we can simplify the whole syntax using the new selectors:
This way, we've made it much easier and faster to code and improved readability by avoiding creating an extended selector.
Simplifying selectors with
:where() is similar to how CSS preprocessors like Sass handle nested rules.
An SCSS file written like this:
After processing becomes:
⚠️ But preprocessors like Sass process their rules nested in a list of selectors, whereas
:is() will treat specificity rules differently, and it's also different from how
:where() handles it.
According to the CSS4 Working Draft:
That is, the specificity of this selector is automatically 🔃 updated to the most specific item in the given argument list.
:where() has no specificity. Its specificity is always zero, making it the first selector resource of its kind in CSS.
Thus, any element selected with this selector automatically gets a specificity of zero. It's so cool that it opens doors and possibilities that were impossible before. ✨
It is now possible for libraries to offer versions without specificity. That way, using them would be much easier if there is wider adoption, as the competition for specificity between authors and library styles could end.
🕯️ I hope I have shed some light on how these powerful selectors work!