How to use Sass

Here's how to create your first Sass file and convert it to CSS automatically.

Now that we have Sass installed, let's go right ahead and create a Sass file. You can do this using your usual code editor such as Brackets, Sublime Text, etc.

We'll create a file called styles.scss. Notice the .scss extension. We'll add the following contents and then save the file.


This will result in the following file.


However, we first need to tell Sass to do this. Right now, if you take a look in the directory where the file resides, you'll see that there's no .css file that corresponds with this file. But we will change that now.

Configure Sass to Watch for Changes

Open your terminal or command prompt, and type the following:

This specifies the SCSS file to watch, and the CSS file to compile the CSS to.

This assumes that you're creating the files in the current directory. If not, you'll need to supply the full path to the files.

You can also specify a whole directory to watch instead of just individual files. To do this, just use the directory paths instead.

You should see a message that reads something like this:

This tells us that Sass has now created a styles.css file to correspond with our styles.scss file. You may also see that a file was created. This is a JSON file that maps the source .scss file with the .css file.

But more importantly, this message also tells us that Sass is now watching for changes. Any change you make to the source .scss file will be reflected in the output .css file.

In fact, if you open the styles.css file now, you should see that Sass has already compiled the Sass code into CSS code:

You can see that the compiled .css file contains only CSS code. It doesn't contain the variables that we set in the Sass file.

The file also has a reference to the .map file that maps this file with the source file.

A Quick explanation of the Sass Code

We created a Sass file that sets two variables. These variables hold colors (but we could've created variables to hold any CSS value — fonts, sizes, border widths, etc). We then used those variables to set the foreground color and background color of the body element.

When the code was compiled to CSS, the variables were removed, and replaced by their values.