I want to do in SCSS something quite simple in vanilla CSS: targeting an element that has two classes.
A simplified example is below:
<div class="parent">
<div class="child"></div>
<div class="child child--red"></div>
<div class="child child--green"></div>
<div class="child child--red child--green"></div>
</div>
I want to target the child that has both child–green and child–red. I tried stuff like below, but it doesn’t work:
.parent {
& > .child {
&--red {
color: red;
}
&--green {
color: green;
}
&--red.&--green {
color: yellow;
}
}
}
I understand why that syntax doesn’t work, considering how the parent selector works, but I’m wondering if there’s an elegant way to do it with the parent selector without having to repeat the child
like:
.parent {
& > .child {
&--red {
color: red;
}
&--green {
color: green;
&.child--red{
color: yellow;
}
}
// OR
&--red.child--green {
color: yellow;
}
}
}
Any idea? Thanks!
2
Answers
To target an element with both child–red and child–green classes in SCSS, you can use nested selectors like this
If you want to maintain that syntax, there are two options (the first is not ideal performance-wise, would probably make sense to just write it out as suggested in the other answer)
Option 1 – Using the
:is
selector allows you to use both on one line:Option 2 – A bit less fluid and not the best to look at, but you can store the name in a variable and reference it this way so that it’s still managed in one place: