sass variables are very useful for storing information. These variables can store following types of data types.
Please keep in mind that place $
symbol before the variable name and place the colon (:)
between the variable name and the value being assigned to it.
$text-font: 30px;
P{
font-size:$text-font;
}
The Sass transpiler creates the following CSS code:
Output:CSS CodeSource Code
<style>
p{
font-size: 30px;
}
</style>
Sass variable will be only available inside the nesting level where the variable is defined.
$textColor: black;
h2 {
$textColor: grey;
color: $textColor;
}
p {
color: $textColor;
}
CSS code output, after the transpilation the above sass code will be:
Source Code
<style>
h2{
color:grey;
}
p{
color:black;
}
</style>
Please keep in mind that variable names can use hyphens and underscores interchangeably hence $heading-font
can access the $heading_font
and vice versa.
$heading_font:30px;
h2{
font-size:$heading_font;
}
Source Code
<style>
h2 {
font-size: 30px;
}
</style>
The Sass variable can also assign a default value that can be only used if the variable does not have a value. To add a default value assign the !defalut
to the end of the variable assignment.
$bg-color: grey;
$bg-color: lightgreen !default;
body {
color: $bg-color;
}
Followings are the CSS code after transpiling the above SCSS code.
Source Code
<style>
$bg-color: grey;
$bg-color: lightgreen !default;
body {
color: $bg-color;
}
</style>
The !global
flag is used to declare a global variable which means that it will be accessible on all the nested levels.
$textColor: green;
h2 {
$textColor: grey !global;
color: $textColor;
}
p{
color: $textColor;
}
After transpiling the above sass, the CSS code will be:
Source Code
<style>
h2 {
color: grey;
}
p{
color: grey;
}
</style>