Variables serve as containers for storing information that can be reused throughout the code.
In Sass, you can store various types of information such as:
To declare variables in Sass, you use the $ symbol followed by a name.
Sass Variable Syntax:
$variablename: value; |
In the following example, four variables—namely myFont, myColor, myFontSize, and myWidth—are declared. Once declared, these variables can be utilized throughout your code as needed.
SCSS Syntax:
$myFont: Helvetica, sans-serif; $myColor: red; $myFontSize: 18px; $myWidth: 680px; body { font-family: $myFont; font-size: $myFontSize; color: $myColor; } #container { width: $myWidth; } |
During the transpilation of the Sass file, the variables (such as myFont, myColor, etc.) are processed, and the resulting CSS incorporates these variables’ values directly into the CSS output.
CSS Output:
body { |
Sass variables remain accessible only within the scope of the nesting level where they are initially defined.
Consider the following illustration:
SCSS Syntax:
$myColor: red; h1 { $myColor: green; color: $myColor; } p { color: $myColor; } |
The color of the text inside a <p>
tag will be red.
Since the definition of $myColor: green;
is within the <h1>
rule, it will solely be accessible within that scope.
Consequently, the CSS output will be:
CSS Output:
h1 { |
That represents the default behavior regarding variable scope.
The default variable scope behavior can be altered by employing the !global switch.
When !global is utilized, it signifies that a variable is global, granting accessibility across all levels.
Refer to the following example (similar to the previous one, but with !global appended):
SCSS Syntax:
$myColor: red; h1 { $myColor: green !global; color: $myColor; } p { color: $myColor; } |
Now, the color of the text inside a <p>
tag will be green.
Hence, the CSS output will be:
CSS Output:
h1 { |