Mastering Sass Variables: Tips and Tricks


Variables in SASS


In Sass, variables are a way to store a value and give it a name that can be reused throughout a stylesheet.

To create a variable in Sass, you can use the $ symbol followed by the name of the variable and then the value you want to assign to it. For example, to create a variable named "primary-color" and assign it the value of "blue", you would write:

$primary-color: blue;

Once you have created a variable, you can use it throughout your stylesheet by calling its name preceded by the $ symbol. For example, if you wanted to use the "primary-color" variable to set the color of a text element, you would write:

.text {
  color: $primary-color;
}

Then, if you decided to change the value of the "primary-color" variable to something else, you could simply update the value of the variable in one place and it would automatically update throughout your stylesheet wherever the variable is used. This makes it easier to maintain consistency and make global changes in your stylesheet.

Source Code


index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SASS Tutorial</title>
    <link rel="stylesheet" href="../css/style.css" />
  </head>
  <body>
    <h1 class="text">Tutor Joe's</h1>
  </body>
</html>
index.scss

$primary-color: blue;
.text {
  color: $primary-color;
}

style.css
.text {
  color: blue;
}