Lesson Weekend

Alright! We've installed Sass, and discussed configuring and compiling it in our own projects. Now we can finally begin writing in it! This lesson will begin our exploration of Sass syntax by exploring one of its basic, yet incredibly useful features: Variables.

Sass Variables

A Sass variable is similar to variables we've already used. It's simply a value attached to a 'nickname'. After defining a variable, we can later call that 'nickname' to represent the entire value.

Defining Variables

But the syntax for defining a Sass variable is different than defining a variable in a language like JavaScript. Check it out, here's the example provided by the Sass Basics guide:

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;

The first two lines define two variables: font-stack and primary-color. Notice the $ preceding each? Sass uses the $ symbol to make something a variable. This is required.

When this code is compiled, Sass automatically places the values for the $font-stack and $primary-color wherever these variables resided in our Sass, like so:

body {
 font: 100% Helvetica, sans-serif;
 color: #333;

This can be extremely powerful in keeping things consistent throughout a site, because if we later want to change that primary-color, we only ever have to change it in one place. This also maximizes the reusability of our styles.

Also, keep in mind that colors and font stacks, as seen in the example above, are not the only types of values that can be attached to a variable. Just like JavaScript, basically any value reused throughout a stylesheet can be defined as a variable!

Required Video: Sass Variables by Net Ninja

Watch the following ~6 minute video from the Net Ninja YouTube channel to observe an example of Sass variables in action:

You're not required to code along, we just want you to get a feel for how developers use Sass variables to refactor styles. But if you'd like to, the starter code used in this video can be found here.