What are variables in Sass, how do you use them and what is the advantage of using variables?

Experience Level: Junior
Tags: Sass

Answer

Variables can be used as placeholders for values. You can then use the variable on multiple places in you Sass file and if you later want to change the value of the variable, you can do it just on one place and the value will then automatically propagate to all the other places where your variable is used.

Variables are declared like this:

Sass:
$errorColor: red;

.alert-box.error {
  color: $errorColor;
}

.button.error {
  background-color: $errorColor;
}
The Sass from above will be compiled to the following CSS:
.alert-box.error {
  color: red;
}

.button.error {
  background-color: red;
}
Note how the variable was replaced by the real value and its declaration is not visible in CSS at all.

Comments

No Comments Yet.
Be the first to tell us what you think.
Sass for beginners
Sass for beginners

Are you learning Sass ? Try our test we designed to help you progress faster.

Test yourself