Sass Variables

sass variables are very useful for storing information. These variables can store following types of data types.

  • strings of text, with and without quotes (e.g. "frontColor", 'frontColor', frontColor)
  • numbers(e.g. 4, 4.5, 10px)
  • colors(blue, #fffc00, rgba(106, 245, 0, 0.8))
  • booleans (e.g. true, false)
  • lists of values, separated by spaces or commas (e.g. 4.5px 12px 0 1px, Helvetica, Arial, sans-serif)
  • nulls (e.g. null)

Sass Variable Syntax:

$<variable name>:<value>;

Please keep in mind that place $ symbol before the variable name and place the colon (:) between the variable name and the value being assigned to it.

Example

SCSS:
    
$text-font: 30px;
P{
  font-size:$text-font;
}
   

The Sass transpiler creates the following CSS code:

Output:CSS Code

General Syntax

      
    
Try it now

Source Code

          <style>
p{
    font-size: 30px;
}
</style>
        
Try it now

Sass Variable Scope

Sass variable will be only available inside the nesting level where the variable is defined.

    
 $textColor: black;
h2 {
  $textColor: grey;
  color: $textColor;
}

p {
  color: $textColor;
}
   

CSS code output, after the transpilation the above sass code will be:

General Syntax

      
    
Try it now

Source Code

          <style>
h2{
	color:grey;
}

p{
	color:black;
}
</style>
        
Try it now

Hyphens & Underscores

Please keep in mind that variable names can use hyphens and underscores interchangeably hence $heading-font can access the $heading_font and vice versa.

    
  $heading_font:30px;
h2{
  font-size:$heading_font;
}
   

CSS Output:

General Syntax

      
    
Try it now

Source Code

          <style>
h2 {
  font-size: 30px;
}
</style>
        
Try it now

Sass Variable Default Value

The Sass variable can also assign a default value that can be only used if the variable does not have a value. To add a default value assign the !defalut to the end of the variable assignment.

    
$bg-color: grey;
$bg-color: lightgreen !default;
body {
  color: $bg-color;
}
   

Followings are the CSS code after transpiling the above SCSS code.

General Syntax

      
    
Try it now

Source Code

          <style>
$bg-color: grey;
$bg-color: lightgreen !default;

body {
  color: $bg-color;
}
</style>
        
Try it now

Using Sass !global

The !global flag is used to declare a global variable which means that it will be accessible on all the nested levels.

    
$textColor: green;
h2 {
  $textColor: grey !global;
  color: $textColor;
}
p{
  color: $textColor;
}
   

After transpiling the above sass, the CSS code will be:

General Syntax

      
    
Try it now

Source Code

          <style>
h2 {
color: grey;
}

p{
  color: grey;
}
</style>
        
Try it now

Web Tutorials

Sass variables
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4