Easy Tutorial
❮ Sass Import Partials Sass Color Func ❯

Sass Variables

Variables are used to store information that can be reused.

Sass variables can store the following information:

Sass variables use the $ symbol:

$variablename: value;

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

After declaring the variables, we can use them in our 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;
}

Converting the above code to CSS, it looks like this:

CSS Code:

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

#container {
  width: 680px;
}

Sass Scope

Sass variables have a scope that is limited to the current level. For example, the h1 style is defined as green within its scope, while the p tag is red.

Sass Code:

$myColor: red;

h1 {
  $myColor: green;   // Local scope, only effective within h1
  color: $myColor;
}

p {
  color: $myColor;
}

Converting the above code to CSS, it looks like this:

CSS Code:

h1 {
  color: green;
}

p {
  color: red;
}

!global

In Sass, we can use the !global keyword to set a variable as global:

Sass Code

$myColor: red;

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

p {
  color: $myColor;
}

Now, the p tag's style will be green.

Converting the above code to CSS, it looks like this:

CSS Code

h1 {
  color: green;
}

p {
  color: green;
}

Note: All global variables are typically defined in a single file, such as _globals.scss, and then included using @include.

❮ Sass Import Partials Sass Color Func ❯