Sass Variables
Variables are used to store information and can be reused.
Sass variables can store the following information:
- String
- Digit
- Color values
- Boolean
- List
- null values
Sass variables use the $ symbol:
$variablename: value;
The following example sets four variables: myFont, myColor, myFontSize, and myWidth.
After declaring a variable, 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 into CSS code as shown below:
CSS code:
body
{
font-family
:
Helvetica
,
sans-serif
;
font-size
:
18px
;
color
:
red
;
}
#container
{
width
:
680px
;
}
Sass Scope
The scope of a Sass variable only takes effect at the current level; as shown below, the h1 style uses the green defined inside it, while the p tag uses red.
Sass code:
$myColor
:
red
;
h1
{
$myColor
:
green
;
// Only valid inside h1, local scope
color
:
$myColor
;
}
p
{
color
:
$myColor
;
}
Convert the above code into CSS code as shown below:
CSS code:
h1
{
color
:
green
;
}
p
{
color
:
red
;
}
!global
Of course, in Sass we can use the !global keyword to make a variable global:
Sass code
$myColor
:
red
;
h1
{
$myColor
:
green
!
global
;
// Global scope
color
:
$myColor
;
}
p
{
color
:
$myColor
;
}
Now the p tag's style will become green.
Convert the above code into CSS code as shown below:
CSS code
h1
{
color
:
green
;
}
p
{
color
:
green
;
}
Note:We generally define all global variables in a single file, such as:_globals.scss, then we use @include to include that file.