Skip to main content

Introduction to Sass Variables

## Sass Variables

Sass variables are used to store a value or a group of values that can be reused throughout a stylesheet. Variables in Sass start with the "$" symbol and are followed by the name of the variable and its value.

As an example:

$primary-color: #1E90FF;

In this example:

  • We're creating a variable called $primary-color and giving it a value of #1E90FF, which is a shade of blue.

Once you've defined a variable, you can use it in your styles like this:

a {
color: $primary-color;
}

In this example:

This will set the color of all links to the value of $primary-color, which in this case is #1E90FF.

You can also use variables to group related values together.

As an example:

$font-sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
$font-serif: Georgia, "Times New Roman", Times, serif;

Then you can use these variables in your styles:

body {
font-family: $font-sans-serif;
}

h1, h2, h3 {
font-family: $font-serif;
}

use variable

Using variables in Sass can make your stylesheets easier to read, maintain, and update, especially if you have multiple styles that share the same values.

Sass Variable Scope​

Variable scope refers to where a variable can be accessed within a stylesheet.

There are two types of variable scope in Sass: global and local.

Global variables are defined outside of any selector or block, and can be accessed from anywhere in the stylesheet.

As an example:

$primary-color: #1E90FF;

body {
color: $primary-color;
}

a {
color: $primary-color;
}

In this example:

  • $primary-color is a global variable that can be accessed from both the body and a selectors.

Local variables, on the other hand, are defined inside a selector or block, and can only be accessed within that selector or block.

As an example:

body {
$primary-color: #1E90FF;
color: $primary-color;
}

a {
color: $primary-color; // This will cause an error, because $primary-color is a local variable defined in the 'body' block
}

In this example:

  • $primary-color is a local variable that can only be accessed within the body selector.
  • If we try to use $primary-color within the a selector, Sass will generate an error because the variable is not defined in that scope.