Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign to a global variable in Sass?

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.

like image 893
mik01aj Avatar asked Dec 04 '22 05:12

mik01aj


2 Answers

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).

like image 91
Gabriela Gabriel Avatar answered Dec 23 '22 09:12

Gabriela Gabriel


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;
like image 23
mik01aj Avatar answered Dec 23 '22 09:12

mik01aj