Variables in Sass
Sass variables are used to store information that can later be used anywhere in the stylesheet when required. The type of information that a Sass variable can store includes colors, numbers, strings, lists, booleans, and nulls.
Syntax
To declare a Sass variable, you must include a dollar ($) sign followed by the variable name, colon, variable value, and a semicolon.
Example
Let’s explore Sass variables further with the help of an example.
HTML
This is our HTML file in which we have created two elements which are a paragraph, and a div container. Meanwhile, the link of the CSS file generated as a result of the compilation of Sass file has been provided to the href attribute of the <link> tag.
Sass
$fontsize: 35px;
$fontcolor: pink;
$border: 2px solid black;
$padding: 10px;
p {
font-family: $fontfam;
font-size: $fontsize;
color: $fontcolor;
}
.container {
padding: $padding;
border: $border;
}
This is our Sass file with .scss extension. Here we have created five sass variables namely $fontfam, $fontsize, $fontcolor, $border, and $padding. Once declared we are then using these variables in our file to style our elements.
CSS
This is our resultant CSS file.
Output
Elements were successfully styled using Sass variables.
Sass Variables Scope
Variables in Sass can be declared anywhere in the document before these are used and can have either a global scope or a local scope.
A Sass variable with a global scope is declared at the beginning of the file and later on used in the entire document where required.
Meanwhile, a Sass variable with a local scope is declared inside a block and can only be used within the scope of that particular block.
Example
The example below demonstrates global and local scoped Sass variables.
Sass
$padding: 10px;
p {
font-family: $fontfam;
font-size: $fontsize;
color: $fontcolor;
}
.container {
$border: 2px solid black;
padding: $padding;
border: $border;
font-size: $fontsize;
}
This is the same code as above with the only difference that $fontsize, and $padding are global variables and can be used anywhere in the file, meanwhile, $border is a local variable and can only be used within the scope of the block it is declared in. This code will have the same output as demonstrated in the previous section. Moreover, the resultant CSS output will also be the same.
Conclusion
Sass variables are used to store information that can later be used anywhere in the stylesheet when required. These variables can store colors, numbers, strings, lists, booleans, and nulls. The name of a Sass variable must begin with a dollar ($) sign and these variables can have either a global scope or a local scope. Moreover, these are a great way to prevent writing redundant CSS values again and again. The article discusses Sass variables in detail along with relevant examples.