Sass Variables

Sass Variables

Variables are a way to store information that you can reuse later.

Through Sass, you can storeinformationstored in variables, for example:

  • string
  • number
  • color
  • boolean
  • list
  • null

Sass uses the $ symbol followed by a name to declare variables:

Sass Variable Syntax:

$variablename: value;

The following example declares 4 variables:

  • myFont
  • myColor
  • myFontSize
  • myWidth

After declaring variables, you can use these variables at any location:

SCSS Syntax:

$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 18px;
$myWidth: 680px;
body {
  font-family: $myFont;
  font-size: $myFontSize;
  color: $myColor;
}
#container {
  width: $myWidth;
}

Therefore, when Sass files are transpiled, they use variables (myFont, myColor, etc.) and output regular CSS along with the variable values placed in the CSS, as follows:

CSS Output:

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

Sass Variable Scope

Sass variables are only available at the nested level where they are defined.

Please see the following example:

SCSS Syntax:

$myColor: red;
h1 {
  $myColor: green;
  color: $myColor;
}
p {
  color: $myColor;
}

<p> The text color within the tag is either red or green? It's red!

Another definition, $myColor: green; is located <h1> within the rule, and it is only available there!

So, the CSS output will be:

CSS Output:

h1 {
  color: green;
}
p {
  color: red;
}

Alright, this is the default behavior of variable scope.

Using Sass !global

You can use !global Switches override the default behavior of variable scope.

!global indicating that the variable is global, which means it can be accessed at all levels.

See the following example (the same as above, but with !global):

SCSS Syntax:

$myColor: red;
h1 {
  $myColor: green !global;
  color: $myColor;
}
p {
  color: $myColor;
}

Now <p> The text color within the tag will be green!

So, the CSS output will be:

CSS Output:

h1 {
  color: green;
}
p {
  color: green;
}

Tip:Global variables should be defined outside any rules. It is wise to define all global variables in their own file, named "_globals.scss", and use @include Keywords include this file.