Variable scope tells us where a variable can be used in our styles. It helps keep styles organized and avoid mistakes.
0
0
Variable scope (global vs local) in SASS
Introduction
When you want to reuse a color or size in many places.
When you want a variable to only affect styles inside a specific block.
When you want to change a variable temporarily inside a function or mixin.
When you want to avoid accidentally changing a variable used elsewhere.
When you want to keep your code clean and easy to understand.
Syntax
SASS
$variable-name: value; // global @mixin example { $variable-name: new-value !global; // change global variable inside mixin } .selector { $variable-name: local-value; // local variable inside selector }
Variables declared outside any block are global by default.
Use !global to change a global variable inside a nested block.
Examples
This uses a global variable
$color inside a selector.SASS
$color: blue; .button { color: $color; // uses global blue }
Inside
.button, $color is local and red. Outside, it stays blue.SASS
$color: blue; .button { $color: red; color: $color; // uses local red } .alert { color: $color; // uses global blue }
The mixin changes the global
$color to green using !global.SASS
$color: blue; @mixin change-color { $color: green !global; } @include change-color; .alert { color: $color; // now green }
Sample Program
This code shows two boxes. The .button uses a local $main-color of red. The .alert uses the global $main-color which is blue.
SASS
$main-color: blue; .button { $main-color: red; background-color: $main-color; color: white; padding: 1rem; border-radius: 0.5rem; } .alert { background-color: $main-color; color: white; padding: 1rem; border-radius: 0.5rem; }
OutputSuccess
Important Notes
Local variables only exist inside the block where they are declared.
Global variables can be read anywhere but to change them inside a block, use !global.
Using scopes helps avoid accidentally changing variables used in other parts of your styles.
Summary
Global variables are set outside blocks and can be used anywhere.
Local variables are set inside blocks and only work there.
Use !global to update a global variable inside a nested block.