Sass Tutorial

Sass HOME Sass Intro Sass Installation Sass Variables Sass Nesting Sass @import Sass @mixin Sass @extend

Sass Functions

Sass String Sass Numeric Sass List Sass Map Sass Selector Sass Introspection Sass Color

Sass Exercises

Sass Quiz

Sass Variables

Variables are a way to store information that you can re-use later.

In Sass, you assign a value to a name that begins with $ symbol and then you can refer to that name instead of the value itself. But despite their simplicity, they're one of the most useful tools Sass brings to the table. Variables make it possible to reduce repetition, do complex math, configure libraries, and much more.

In Sass, we can store information in variables, like-

  • strings
  • numbers
  • colors
  • booleans
  • lists
  • nulls

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

$variablename : value;

The following declares a variable named large-font

$large-font: 50px;

Let's a example declares with 4 variables named myFont, myColor, myFontSize, and myWidth. After the variables are declared, you can use the variables wherever you want:

SCSS Syntax

$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 12px;
$myWidth: 350px;

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

#container {
  width: $myWidth;
}


So, when the Sass file is transpiled, it takes the variables (myFont, myColor, etc.) and outputs normal CSS with the variable values placed in the CSS, like this:

CSS Output

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

#container {
  width: 350px;
}

Sass Variable Scope

Variables are only available at the level of nesting where they're defined.

Let's look at an example

SCSS: Variable Scope

$myColor: red;

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

p {
  color: $myColor;
}

Above, will the color of the text inside a <p> tag be red or green? It will be red!

The other definition, $myColor: green; is inside the <h1> rule, and will only be available there!

So, the CSS output will be

CSS Output

h1 {
  color: green;
}

p {
  color: red;
}

it is the default behavior for variable scope.

Sass !global

The default behavior for variable scope can be overridden by using the !global switch.

!global indicates that a variable is global, which means that it is accessible on all levels.

Add !global in above example:

SCSS: !global

$myColor: red;

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

p {
  color: $myColor;
}

Now the color of the text inside a <p> tag will be green!

CSS Output

h1 {
  color: green;
}

p {
  color: green;
}

Global variables should be defined outside any rules. It could be wise to define all global variables in its own file.

To know about Nesting in SASS. We will learn in next chapter Click