How to assign to a global variable in Sass?

Solution 1:

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 using feature-exists(global-variable-shadowing).

Solution 2:

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;