Sass Variable

If you never use any of the other capabilities of Sass, variables would be enough to justify the extra step of transpiling your CSS. We've already looked at why variables are so useful. Now let's take a closer look at how to declare them.

The basic syntax for defining a variable is simple: Just use a $ before the variable name and treat its definition like a CSS rule:

Sass Variable Syntax:
$<variable name>:<value>;

The following declares a variable named large-font.

$large-font: 50px;

Once it's been declared, you can use the variable just as though you were typing the variable:

SCSS:
$large-font: 50px;

p {
    font-size: $large-font;
}

The Sass transpiler will handle the substitution for you:

CSS:
p {
    font-size: 50px;
}

There's only one "gotcha" in declaring variables: For historical reasons, a hyphen and an underscore are interchangeable. Look at the following example.

SCSS:
$main-color: red;

p {
   color: $main-color; /* variable with hyphen */
}

a {
   color: $main_color;/* variable with underscore */
}

In the above example, both of the elements will display text in red.

Scope

Like any modern programming language, Sass variables support the concept of scope: Variables are only available at the level of nesting where they're defined. Let's look at an example:

SCSS: Variable Scope
$main-color: red;

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

a {
  color: $main-color;
}

Can you figure out what color the text inside an <a> tag will be? It will be red. The second definition, $main-color: blue; is inside the rule for the <p> tag, and will only be available there. The following is transpiled CSS.

CSS:
p {
   color: blue;
}

a {
   color: red;
}

That's the default behavior. You can override it by using the !global switch:

SCSS: !global Switch
$main-color: red;

p {
   $main-color: blue !global;
   color: $main-color;
}

a {
  color: $main-color;
}

which will result in

CSS:
p {
   color: blue;
}

a {
   color: blue;
}

In this code, the text inside the <a> tag will be blue. But the !global switch, like it's siblings !important and !default, have side-effects that can be hard to predict or track down, so use them with care. As a general rule, if you want a variable to be global, define it outside any rules. Best practice is to define all your global variables in a single file, named _globals.scss by convention, and include it using @include anywhere it's needed.

Learn more about SassScript expressions in the next chapter.