Skip to content

Try our new Crash Courses!

Become a member using the button below to hide this banner and gain access to our new Crash Courses.

Variables – Sass

Demo

Summary

In Sass, variable names start with a dollar sign:

$main-color: red;

h1 {
  color: $main-color;
}

p {
  background-color: $main-color;
}

Compiled CSS:

h1 {
  color: red;
}

p {
  background-color: red;
}

To see a live example of this code, click the link in the Demo section below.

Details

Sass variables allow you to reuse the same value in multiple spots in your style sheet. This is accomplished by storing a value in a variable name and then referencing that variable name throughout your style sheet (see the code above for an example). You can store any CSS value: a color, a font, a width, etc.

Variables in Sass start with a dollar sign and don’t have to be wrapped in curly brackets. They use the following format:

$variable-name: value;

Using variables also means it’s easy to update multiple CSS rules at once. In the example above, I can change the $main-color variable to blue, which will automatically update the color property of the h1 tag and the background-color property of the p tag in the compiled CSS. This is easier than having to manually update each CSS rule where the color appears.

More Examples

// Sass variable storing fonts
$font-stack: Helvetica, sans-serif;

// Sass variable storing a width value
// Note: Variable names can be one word
$width: 100px;

body {
  font: 100% $font-stack;
}

.rectangle {
  width: $width;
}

Exercises

First, recreate the Sass code in the embedded CodePen demo.

Then try changing the value in the variable.

References

Sass Basics | Sass

Variables | Sass Documentation

Back to: Sass Reference