Using Variables with SASS Tutorial

Using Variables with SASS Tutorial

An Introduction to Using Variables with SASS

SASS effectively gives us a lot of the programmatic benefits of working with code, only now with the ability to apply it to stylesheets.

Over the next few posts, we’ll be diving right into the features of SASS.

First up let’s introduce variables.

Definition

Variables are a way to store information that you want to reuse throughout your stylesheet.

They allow us to store values for colors, fonts, or really any CSS value that you want to reuse!

We use the $ symbol when we wish to make something a variable.

Example

In our SCSS, let’s define a color variable:

$color-primary: #ffff00; // Yellow

body {
  background-color: $color-primary;
}

This will, of course, set our background-color to yellow. It’s that simple!

Note: You can use single-line comments in Sass with //.

When we then run our compile, it’ll output the following CSS:

body {
  color: #ffff00;
}

Note: We'll be covering the compilation process further on in this series. For now, it’s good to know that when we save our code into sass/main.scss, it’ll automatically compile into the css/style.css file!

This becomes extremely powerful when working on large projects!

If you wish to make a change to a color used throughout your stylesheets, it’s much simpler to alter if the color is defined in one location as a single variable.

The alternative to changing the value of one variable defined at one location is finding and replacing every reference to the value you want to change. This is a much more tedious task, especially if you want to implement a quick change to test out a different color or font.

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!

🌎 Let's Connect

Did you find this article valuable?

Support Richard Rembert by becoming a sponsor. Any amount is appreciated!