How to assign to a global variable in Sass?

梦想与她 提交于 2019-12-17 04:35:08

问题


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.


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




回答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;


来源:https://stackoverflow.com/questions/26260790/how-to-assign-to-a-global-variable-in-sass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!