Suppose I'd like to define a global value for a variable, then override it for specific selectors. According to the SASS documentation this should be possible.
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.
Logic would then state that "green" and "red" as values for $text-color
would only be available within their respective nested selectors, and that $text-color
would take a value of "blue" when called anywhere else, such as within .foo
.
$text-color: blue;
.green {
$text-color: green;
color: $text-color;
}
.red {
$text-color: red;
color: $text-color;
}
.foo {
color: $text-color;
}
This is not the case, however, and the above SASS compiles to:
.green {
color: green;
}
.red {
color: red;
}
.foo {
color: red;
}
Any help understanding this would be, well, helpful.
Sass variables have scope, just like they would in JavaScript, Ruby, or any other programming language. If declared outside of a selector, the variable is available to every selector in the document after its declaration.
Interpolation allows us to interpolate sass expressions into a simple SASS or CSS code. Means, you can define ( some part or the whole ) selector name, property name, CSS at-rules, quoted or unquoted strings etc, as a variable. Interpolation is a new principle and it is widely used in SASS.
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
This is an old question, but for the record, as of version 3.4.0, variables are now block-scoped unless marked with the !global flag.
From the changelog:
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).
This means that this scss
:
$color: red;
.sel {
$color: green;
color: $color;
}
.sel2 {
color: $color;
}
Will now produce the following css
:
.sel {
color: green;
}
.sel2 {
color: red;
}
This is because once you assign a variable to be global, all further assignments to that variable are done globally too. If you want to make it local after that, you could do $local-text-color: $text-color;
and then color: $local-text-color;
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