
Question:
As you can see, I have a variation for .mainContainer
in the form of &--alt
. However, I need to repeat .mainContainer__content
inside the &--alt
class to say that if there's a .mainContainer--alt
in the parent container, then .mainContainer__content
will have a different styling.
Is there a better way to write this as it seems to defeat the purpose of using the shorthand version if I am going to write out the complete class name in this particular example.
CSS:
.mainContainer {
// SOME CSS properties
&--alt {
.mainContainer__content {
// SOME CSS properties
}
}
&__content {
// SOME CSS properties
}
}
HTML:
<div class="mainContainer">
<div class="mainContainer__content">
// some style
</div>
</div>
HTML (with alt):
<div class="mainContainer mainContainer--alt">
<div class="mainContainer__content">
// some other style
</div>
</div>
Answer1:You can save the main class in a variable like this
.mainContainer {
$self: &;
// SOME CSS properties
&--alt {
#{$self}__content {
// SOME CSS properties
}
}
&__content {
// SOME CSS properties
}
}
Another option is to put the modifier on the<br />.mainContainer__content
e.g. .mainContainer__content--alt
check this link: <a href="https://www.w3schools.com/Css/css_attribute_selectors.asp" rel="nofollow">https://www.w3schools.com/Css/css_attribute_selectors.asp</a>
I uesed attribute selector where class ends with [class$="value"]
.mainContainer {
// SOME CSS properties
&[class$="--alt"] {
.mainContainer__content {
// SOME CSS properties
}
}
&[class$="__content"] {
// SOME CSS properties
}
}
but again I dont recommend write it this way.
Answer3: