This content originally appeared on Bram.us and was authored by Bramus!
# To :is()
or not to :is()
?
Consider this following complex selectors:
.a .b .c {
background: green;
}
.a :is(.b .c) {
background: green;
}
They might look the same, but they behave differently … the second selector selects more than you might initially think.
~
# Try it out
See the Pen CSS Nesting: The implications of :is() by Bramus (@bramus) on CodePen.
~
# Explanation
Selectors matching happens from right to left. That means that for these complex selectors it will start with its last unit (part) and then move up the chain.
.a .b .c
-
This selector contains 3 units:
.a
,.b
, and.c
. When trying to find matching elements, the browser will first select all.c
elements and will then check if they have a.b
parent. If that’s the case, it will then check if that.b
is a child of a.a
element. .a :is(.b .c)
-
This selector contains 2 units:
.a
, and:is(.b .c)
. The first evaluated unit:is(.b .c)
, which matches the.c
elements that sit inside a.b
. If that’s true, the browser will then continue and check if that match – the.c
– also has a.a
ancestor.
~
# Why is this relevant?
There’s an active discussion within the CSS Working Group on whether CSS Nesting should expand the &
using :is()
or not.
Consider this nested block:
.a .b {
.c & {
background: green;
}
}
When expanding &
to the outer selector wrapped inside a :is()
– as it is currently specified in the spec – that snippet would become:
.a :is(.b .c) {
background: green;
}
This might be counterintuitive for authors who have used Sass and other preprocessors before. Sass simply replaces the &
with the outer selector:
.a .b .c {
background: green;
}
As demonstrated in this post, these behave differently.
~
# Anything else about :is()
?
As mentioned in an earlier post, there’s more things to know about :is()
:
- The selector list of
:is()
is forgiving - The specificity of
:is()
is that of its most specific argument :is()
does not work with pseudo-element selectors (for now)
See https://brm.us/css-is for more details
~
# Spread the word
To help spread the contents of this post, feel free to retweet its announcement tweet:
Using `:is()` in complex selectors selects more than you might initially think.
🏷 #css #selectors pic.twitter.com/uN9wIAZ2Zm
— Bram.us (@bramusblog) January 17, 2023
~
🔥 Like what you see? Want to stay in the loop? Here's how:
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2023-01-17T20:33:25+00:00) Using :is() in complex selectors selects more than you might initially think. Retrieved from https://www.scien.cx/2023/01/17/using-is-in-complex-selectors-selects-more-than-you-might-initially-think/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.