Sass Variables

Variables are used to store information that can be reused.

Sass variables can store the following information:

  • Strings
  • Numbers
  • Color values
  • Booleans
  • Lists
  • null values

Sass Variable Usage$Symbol:

$variablename: value;

The following example sets four variables: myFont, myColor, myFontSize, and myWidth.

After declaring the variables, we can use them in the code:

Sass code:

$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 18px;
$myWidth: 680px;

body {
  font-family: $myFont;
  font-size: $myFontSize;
  color: $myColor;
}

#container {
  width: $myWidth;
}

Convert the above code to CSS code, as shown below:

CSS code:

body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: red;
}

#container {
  width: 680px;
}

Sass Scope

The scope of a Sass variable only takes effect at the current level. For example, h1's style is green, as defined inside it, while the p tag is red.

Sass code:

$myColor: red;

h1 {
  $myColor: green;   // Only useful inside h1, local scope
  color: $myColor;
}

p {
  color: $myColor;
}

Convert the above code to CSS code, as shown below:

CSS code:

h1 {
  color: green;
}

p {
  color: red;
}

!global

Of course, in Sass we can use the!globalkeyword to set a variable as global:

Sass code

$myColor: red;

h1 {
  $myColor: green !global;  // Global scope
  color: $myColor;
}

p {
  color: $myColor;
}

Now the style of the p tag will become green.

Convert the above code to CSS code, as shown below:

CSS code

h1 {
  color: green;
}

p {
  color: green;
}

Note:All global variables are generally defined in the same file, for example:_globals.scss, then we use@includeto include the file.

Other Extensions