How to use Sass Variables?

Last updated on January 19, 2023

SASS is Syntactically Awesome Stylesheet, if you are working with CSS then you should learn SASS as well, sass is an extension of CSS and Sass is a CSS preprocessor, obviously, Sass reduces the coding time and allow the user to declare the variables and store the repetitive properties in it.

For example, working with a theme, the color codes and fonts are repetitive properties which can be stored in the variables. And these variables we can use in too many code blocks, another benefit of the usage of variables is we can change the entire color schemes and fonts only by replacement of the variables values.

In this article, we will cover the sass variables with examples. As we know the CSS does not allow us to create variables.

Scope of Variable in Sass

Sass variable name starts with the $ symbol, variables in the sass can be declared anywhere in the sass document before it is used. There are two types of variables in the sass, Global Variables and local or Scoped Variables.

Global Variables

Global variables mean these variables can be accessed anywhere in the document so it is necessary to declare them at the beginning of the document.

$primary-color: #000;
$white:#ffffff;
.header{
 background: $primary-color;
 color: $white;
}

In this example we can access both color variables anywhere in the document and we can change the color schemes by only replacing the color code.

Local or Scoped Variables

In this example we declare variables inside of the code block, so these variables can be available only in the code block or class. These variables are called scoped or local

.header{
$primary-color: #000;
$white:#ffffff;
 background: $primary-color;
 color: $white;
}

In this example we declare variables in the side of the code block, so these variables can be available only in the code block or class.

Conclusion

SASS is Syntactically Awesome Stylesheet, which allows using the variables, by using the variables in the stylesheet can reduce the time and effort, another benefit of the usage of variables is easy to change the value which reflects on the entire document.
Sass provides two types of variables global and local or scooped, a global variable can be accessed anywhere in the document. It is necessary to declare it at the top of the document.
A local or scoped variable needs to be declared inside of the code block and it cannot be accessible for another code block.
A sass variable starts with a $ symbol then its name along with its value. ($variableName: value)


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: CSS,