Variable area in SASS

Suppose I want to define a global value for a variable, and then override it for specific selectors. According to the SASS documentation, this should be possible.

Variables are only available within the nested selector level where they are defined. If theyre defined outside of any nested selectors, they are available everywhere.

Logic would then state that โ€œgreenโ€ and โ€œredโ€, since the values โ€‹โ€‹for $text-color would only be available within their respective nested selectors, and that $text-color would take on a value of โ€œblueโ€ when called elsewhere, for example like inside .foo .

 $text-color: blue; .green { $text-color: green; color: $text-color; } .red { $text-color: red; color: $text-color; } .foo { color: $text-color; } 

However, this is not the case, and the above SASS compiles:

 .green { color: green; } .red { color: red; } .foo { color: red; } 

Any help in understanding this would be helpful.

+7
source share
2 answers

This is due to the fact that after you assign a variable to global, all further assignments to this variable are also performed globally. If you want to make it local after that, you can do $local-text-color: $text-color; , and then color: $local-text-color;

+9
source

This is an old question, but for recording, starting with version 3.4.0, variables now break off with blocks if they are not marked with a global flag!

From the change log:

All variable assignments not at the top level of the document are now locally by default. If a global variable with the same name exists, it will not be overwritten if the global flag is not used. For example, $ var: value! Global assigns $ var globally.
This behavior can be detected using the Function-exists (globally variable shading).

This means that this scss :

 $color: red; .sel { $color: green; color: $color; } .sel2 { color: $color; } 

Now you will get the following css :

 .sel { color: green; } .sel2 { color: red; } 
+12
source

All Articles