Is there a way to add a class to the first element of a nested selector with .scss? Imagine the example below:
body p {
color: black;
}
body.other-mode p {
color: red;
}
Would it be possible to express it like this (or in a similar way, since this won't compile)
body p {
& {
color: black;
}
.other-mode& {
color: red;
}
}
I'm aware this can be written like this, but that's just a different way of "solving" an example of the issue.
body {
& p {
color: black;
}
&.other-mode p {
color: red;
}
}
I also tried using some scss selectors but they don't work quite as expected, in the case below the selectors ends up being body p body.other-mode p
instead of body p
body p {
& {
color: black;
}
#{selector-replace(&, "body", "body.other-mode")} {
color: red;
}
}
CodePudding user response:
To make your last solution work, you can use @at-root.
body p {
& {
color: black;
}
@at-root #{selector-replace(&, "body", "body.other-mode")} {
color: red;
}
}
compiles to
body p {
color: black;
}
body.other-mode p {
color: red;
}
But personally, I find your original solution the most readable.
body { &.other-mode p {color: red;} }
I find the split body
and p
more convenient in SCSS.