Starting your journey with Sass

an introduction to using a popular CSS preprocessor called Sass

Posted by Wazoo on November 01, 2018 · 14 mins read

sass

Sass is a CSS preprocessor that can make writing CSS faster, more efficient and easier to maintain. You might have heard of Sass, but not know how to set it up or integrate it with your projects. We’ll go over all of that in this tutorial.

Prerequisities

  • Basic knowledge of CSS
  • Basic knowledge of Node / NPM
  • Basic knowledge of the command line

Goals

  • Learn what a CSS preprocessor can do
  • Install the necessary prerequisites for Sass
  • Use the command line to compile SCSS into CSS
  • Create a Sass project

What is a CSS preprocessor?

A preprocessor is a program that takes one bit of code and compiles it into a different bit of code. In the case of CSS preprocessors, we’re taking a file written with Sass syntax, and converting it into regular CSS that the browser can work with.

The code you use on your HTML page will be the same as with CSS; all the preprocessing will happen behind the scenes.

<link href="style.css" rel="stylesheet" />

LESS or Sass? Which should I use?

LESS and Sass are both CSS preprocessors, that do the same thing with the same end goal, but follow slightly different markup and syntax.

LESS and Sass are more similar than they are different. However, Sass is more popular being more widely used across a number of projects and frameworks. Big name teams regularly turn to Sass if they haven’t already - for example, when the Twitter Bootstrap developers upgraded the framework from version 3 to 4, they moved from LESS to Sass.

What’s the difference between Sass and SCSS?

When I refer to Sass in this article, I’m referring to the entire Sass project. Within the Sass project, there are two different preprocessors to choose from:

  • Sass - Syntactically Awesome StyleSheets - the .sass extension
  • SCSS - Sassy CSS - the .scss extension

Throughout this article we’re going to use SCSS. SCSS is more widely used, and I’ve found that it’s much easier to get started with and integrate into existing projects - in fact, if you take any .css file and save it as a .scss file; TADA! It is now a valid SCSS file.

SCSS uses all the syntax you’ve become accustomed to in CSS; namely the use of semi-colons and curly brackets.

p {
  font-size: 1em;
}

Sass does away with the syntax, and relies on forced indentation.

p
  font-size: 1em

It may seem cleaner and easier from a glance, however you can imagine it is an extremely non-trivial task to convert the CSS of an existing project into Sass syntax format. For largely this reason alone, most reach for SCSS.

Why should I learn Sass? How will it help me?

There is a bit of a learning curve when it comes to using and setting up Sass. You should already be proficient, or at least competent with CSS before attempting to learn a CSS preprocessor. In other words, using the preprocessor won’t magically teach you CSS.

If you’ve ever had to change a color multiple times throughout your stylesheet and wished there was a better way, or had your stylesheet covered with vendor prefixes, or noticed that it’s not long before your main stylesheet was long and difficult to maintain, that’s enough reason to consider another way of working with your CSS.

The Sass Guide provides some excellent onboarding in their official documentation to understand what Sass can do. It’s worth spending a few minutes going over the guide. Rather then try to re-explain The Guide (cough), I’ll just pull out a few key features:

  • Variable - A variable is a storage container (eg. placeholder) for a CSS value, such as a color or number. The syntax is written as $variable. You can use this code throughout the stylesheet after you have defined it.
  • Nesting - Nesting reduces repetition in code and makes writing CSS faster and easier.
  • Partials - Partials are SCSS files that begin with an underscore (_partial.scss) and are not compiled into their own CSS files, but are rather imported into a main file.
  • Import - Use @import to compile all your partials into one file.
  • Mixins - Use @mixin for repetitious CSS, such as when vendor prefixes are required.
  • Extend - Use @extend to change a few key aspects of otherwise identical elements - such as a group of buttons with different colors.
  • Operators - Operators allow you to use math calculations in your CSS - such as defining the width of various parts of a layout.

Installing Sass

Up until recently, Sass was packaged as a Ruby gem, which made it necessary to install Ruby on your machine. Not that big a deal in and of itself, however it would sometimes make integration with other frontend tooling interesting.

However these days, the node-sass project exists, and is an easier way to incorporate Sass construction by itself or integrating with existing frontend workflow tooling.

As such, NPM is going to be our preferred choice here.

  • mkdir start-sass
  • cd start-sass
  • npm install node-sass -g

This will install the node-sass compiler in your global node library area.

We’re ready to go!

Compile a SCSS file into a CSS file

Within the same folder, create a new file

touch style.scss

The style.scss file will be a simple test to ensure we can compile the file. As a reminder, we cannot reference this file directly in our HTML markup. Nothing would happen as the browser won’t “understand” how to work with the .scss reference.

We need to first compile it to CSS. I’m creating a variable that contains a color, and applying that color to the h1 tag.

$primary-color: #6495ED;

h1 {
    color: $primary-color;
}

Now let’s compile the file. This is done by typing node-sass followed by the name of your scss file, followed by the CSS filename you want it to compile into.

node-sass style.scss style.css

Congratulations, you’ve successfully compiled a SCSS file! As you can see in the same folder, we generated a regular .css file.

h1 {
  color: #6495ED; }

This is good, and it works. However, it would start to be annoying if you had to run this command every time you wanted to make a change to a file. Fortunately, we can remedy this with a Sass watch.

Watch for changes and compile automatically

Using node-sass --watch, the process running the Sass compiler will notice every time you make a change to your file and compile it to CSS.

node-sass --watch style.scss style.css

Now, when you make any change to the style.scss file, you’ll notice some output…

=> changed: C:\git-root\start-sass\style.scss
Rendering Complete, saving .css file...
Wrote CSS to C:\git-root\start-sass\style.css

This is pretty cool!

Now what happens when we have an error in our SCSS file? Let’s go back and make a very obvious typo (remember the --watch should still be running)

$primary-color: #6495ED;

h1 {
    color: $primary;
}

What happens? In the console window you should now see…

=> changed: C:\git-root\start-sass\style.scss                                                                                       
{                                                                                                                                   
  "status": 1,                                                                                                                      
  "file": "C:/git-root/start-sass/style.scss",                                                                                      
  "line": 4,                                                                                                                        
  "column": 10,                                                                                                                     
  "message": "Undefined variable: \"$primary\".",                                                                                   
  "formatted": "Error: Undefined variable: \"$primary\".\n        on line 4 of style.scss\n>>   color: $primary;\r\n   ---------^\n"
}                                                                                                                                                                                                                                                                  

Not too shabby at all. The error message is quite clear - undefined variable "$primary"

In today’s environments, it’s not only pretty common for us to have many many (many) browser tabs open, but we also to have quite a few different application windows open at any time. While --watch is incredibly useful, it may become a little annoying tabbing back and forth between the terminal window and our code editor, while we verify if we’ve used correct Sass syntax.

A handy trick I use, is to also use the --error-bell flag. When an error is detected, an audible bell will sound.

Let’s try it out.

  • Hit Ctrl+C to stop the node-sass process
  • Restore the style.scss file so that it’s valid sass syntax
  • Run node-sass --watch --error-bell style.scss style.css
  • Once the process is running, go back and make any syntax error in the sass

You should now hear a bell sound along with the error message in the console window.

Creating a Sass project

One of the great things about Sass, and perhaps the entire point of it, is being able to organize your CSS. Instead of having one huge CSS file that becomes hard impossible to maintain, you can break down all the components of your site into multiple files known as partials, and compile them into one, CSS file.

Thanks to --watch, any change made to these partials will be detected, and the main file will be updated.

I’m going to create a very simple example of a Sass project. We’re going to create just a src folder and put our SCSS files in there. Node-sass will take care of creating our output .css file which will be in a folder that we’ll call dist.

\---src
    |   main.scss
    |
    +---base
    |       _palette.scss
    |       _variables.scss
           _typography.scss
    |
    \---components
            _buttons.scss
            

Just to make it obvious, let’s walk through what we’re going to do. Our “root” main.scss file will contain .scss files from the base and components directories.

In the base, I usually try to keep it to global / project-wide type of settings. Your main colors, font-families, and h1-h6, p, etc. type of declarations.

Then in components, I try to put declarations and variables that deal with forms and/or “gui” - things like button, input, and select for example.

As you get more comfortable with Sass, you can structure your project however you want.

So let’s start with main.scss:

// main.scss

@import 'base/palette';
@import 'base/variables';
@import 'base/typography';

@import 'components/buttons';

Notice how we’re declaring the @import of our partials. The filenames of our partial begins with an _, and when we declare them in the @import we drop the leading _, along with the scss extension.

Now, let’s setup node-sass to watch the entire project and process everything into one single file in the dist folder.

node-sass --watch src/main.scss dist/styles.css

TADA! As you make changes to your Sass project, you’ll see the resultant output in the dist/styles.css file.

Conclusion

In this tutorial, we started the journey towards using CSS preprocessing using Sass. It may not fit every project, but it’s definitely a handy tool to get to know. In a future tutorial, maybe I’ll cover more Sass syntax. Hope you enjoyed it!