π :is() and :where()
Β·3 min read
Both selectors (:is()
and :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 :is()
and :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:
"The specificity of the
:is()
pseudo-class is replaced by the specificity of its most specific argument. Thus, a selector written with:is()
does not necessarily have equivalent specificity to the equivalent selector written without:is()
."
That is, the specificity of this selector is automatically π updated to the most specific item in the given argument list.
Meanwhile, :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!