Sass Variables

One the most persuasive reasons for using Sass was introduction to variables, which was not possible in CSS at the time of Sass's introduction. However, even with the addition of CSS Variables, Sass Variables still have some advantages.

Sass Variables begin with a $ and the name of the variable. A colon (:) is used to separate the variable from the value or expression. To use a variable, simply call the variable inside of a style rule.

Sass Variables can be used anywhere in the code and store almost any kind of data. One common use for Sass variables is storing colors.

$offwhite: #EEE8D6;
$darkblue: #022933;

body {
  color: $offwhite;
  background-color: $darkblue;
}

The above code will compiled to the following CSS.

body {
  color: #EEE8D6;
  background-color: #022933;
}

Sass Variables vs CSS Variables

As mentioned above, CSS now supports variables natively. But they are some very important key difference between the two.

  • Sass variables are read by the Sass compiler and removed from the resulting CSS, while CSS variables are included in CSS and are read by the browser during run time.

  • CSS variables can hold different values for different elements, while Sass variable can only hold one value at a time.

  • If you change the value of a CSS variable all uses of the variable include those that occur before the change will be affected. Whereas if you change the value of a Sass variable, only future uses of the variable will be affected.