I run this Sass code:
$a: 1;
@if 2 + 2 == 4 {
$a: 2;
}
@debug $a;
I expect to see 2. The output, however, is:
Line 5 DEBUG: 1
I understand that Sass creates a new $a
variable inside the @if
scope. How can I change this behaviour and assign a value to the global $a
?
I use Sass 3.4.0.
As you're using Sass 3.4+, you should append the !global
flag to your variable declaration:
$a: 1;
@if 2 + 2 == 4 {
$a: 2 !global;
}
@debug $a; // will output 2
The original SASS_REFERENCE on variable declaration stated:
"Variables are only available within the level of nested selectors where they're defined. If they're defined outside of any nested selectors, they're available everywhere.
but the SASS_CHANGELOG of 3.4+ shows that this behaviour has changed:
All variable assignments not at the top level of the document are now local by default. If there’s a global variable with the same name, it won’t be overwritten unless the
!global
flag is used.For example,
$var: value !global
will assign to$var
globally. This behavior can be detected usingfeature-exists(global-variable-shadowing)
.
By trial-and-error, I found a solution: I have to add !global
in the assignment.
$a: 1;
@if 2 + 2 == 4 {
$a: 2 !global;
}
@debug $a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With