Sass Variables
# Sass Variables
Variables are used to store information that can be reused.
Sass variables can store the following information:
* Strings
* Numbers
* Color values
* Booleans
* Lists
* null values
Sass variables use the $ symbol:
$variablename: value;
The following example sets four variables: myFont, myColor, myFontSize, and myWidth.
After declaring variables, we can use them in our 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 Sass variables only takes effect at the current level. As shown below, the h1 style is green defined inside it, and the p tag is red.
## Sass Code:
$myColor:red;
h1 {
$myColor:green;// Only useful inside 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
Of course, in Sass we can use the !global keyword to set variables as global:
## Sass Code
$myColor:red;
h1 {
$myColor:green!global;// Global scope
color:$myColor;
}
p {
color:$myColor;
}
Now the p tag style will become 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 [@include](#) to include that file.
AI is thinking...
[](#)(#)
(#)[](#)
[ByteArk Coding Plan supports Doubao, GLM, DeepSeek, Kimi, MiniMax and other mainstream large models, official direct supply stable and reliable. Configuration Guide Β₯9.9/month Subscribe now](https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E)
YouTip