We use cookies to enhance your experience on the site
CodeWorlds

Variables in Sass

Variables in Sass are a powerful tool that allows you to reuse values throughout your stylesheet. You can define a value once and then use it in many places, making it easier to maintain your code and implement changes.

Defining Variables

Variables in Sass start with the dollar sign ($). We can assign various values to them, such as colors, lengths, percentages, font names, boolean values, and more.

Example:

1$main-color: #c06;
2$font-stack: Helvetica, sans-serif;
3$base-line-height: 1.5;

Using Variables

After defining variables, we can use them in our CSS declarations by placing the variable name wherever we want to use its value.

Example:

1body {
2  color: $main-color;
3  font: 100% $font-stack;
4  line-height: $base-line-height;
5}

Variable Scope

Variables in Sass have scope, which means they are only available within the block where they were defined. If you define a variable at the top level (outside any selectors or rules), it is globally available and you can use it throughout the stylesheet.

However, if you define a variable inside a rule or selector, it will only be available within that block.

1$global-color: blue;
2
3.foo {
4  $local-color: green;
5  color: $local-color;  // green
6}
7
8.bar {
9  color: $local-color;  // error, $local-color is not available here
10}

Remember that Sass allows you to override variables. If you define a variable with the same name inside a selector, Sass will use the most recent value of that variable.

Variables in Sass are one of the most important tools for maintaining consistent and easily manageable CSS code. Thanks to them, it is possible to create more dynamic and configurable stylesheets.

Go to CodeWorlds