Sass variable
Variables are used to store some information and can be reused.
Sass
variables can store the following information:
String
Figures
Color value
Boolean value
List
Null value
Sass
variable use $
symbol:
$variablename: value;
The following example sets four variables: myFont
, myColor
, myFontSize
, and myWidth
.
After the variable is declared, we can use it in the code:
Sass
code:
$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 18px;
$myWidth: 680px;
body {
font-family: $myFont;
font-size: $myFontSize;
color: $myColor;
}
#container {
width: $myWidth;
}
Convert the above code to CSS code, as follows:
Css Code:
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
#container {
width: 680px;
}
Sass scope
The scope of a Sass
variable can only have an effect at the current level, as follows the h1
style of the green
, p
tag is for red
.
Sass
code:
$myColor: red;
h1 {
$myColor: green; // Only useful in h1, local scope
color: $myColor;
}
p {
color: $myColor;
}
Convert the above code to CSS code, as follows:
Css Code:
h1 {
color: green;
}
p {
color: red;
}
!global
That’s for sure Sass
, we can use the !global
keyword to set the variable is global:
Sass
code
$myColor: red;
h1 {
$myColor: green !global; // Global scope
color: $myColor;
}
p {
color: $myColor;
}
Now the p
style of the label becomes green
.
Convert the above code to CSS code, as follows:
Css code
h1 {
color: green;
}
p {
color: green;
}
Note: all global variables are generally defined in the same file, such as:\_globals.scss
and then we use the @include
to include the file.