Reputation: 31
I am trying to override a SASS variable like so:
.component {
$background: red;
// Variations
&.component--blue {
$background: blue;
}
&.component--green {
$background: green;
}
// lots of styling in-between
a {
background: $background;
}
}
HTML:
<div class="component">
<a href="#">Test</a>
</div>
<div class="component component--green">
<a href="#">Test</a>
</div>
Unfortunately with the above code the a tag with in the component always has a green background. I would have expected to be red on the first and green on the second. Am I missing something? I have looked up the documentation here: https://sass-lang.com/documentation/variables#scope
As far as I can see this should be possible, but maybe not..
Could anybody enlighten me? Many thanks!
Upvotes: 1
Views: 80
Reputation: 32
Since a variable can hold only one value at a time, the $background variable is taking the latest value assigned to it.
I would suggest using below code:
$background-red: red;
$background-blue: blue;
$background-green: green
and then use the following
&.component--blue {
background: $background-blue;
}
&.component--green {
background: $background-green;
}
Hope this helps! :)
Upvotes: 1
Reputation: 334
The idea is that you cannot change variables following CSS conditions because they are compiled before any browser CSS interpretation.
Take a look at CSS VAR which are a perfect alternative in your case. var()
are well supported.
Upvotes: 0