Beginner's guide to Sass

And why Sass?


Sass logo

CSS keeps evolving. One of the biggest milestones is variables in CSS. But there are still tedious tasks left. Imagine you need to write multiple sets of similar styles in your stylesheet. Even if you create special classes for each variation, CSS still doesn't offer a way to override them. And what if you want to update or replace a single value across the entire stylesheet?

With Sass, you can override styles and values—and changing a value in one place can update the entire stylesheet, which plain CSS variables can't fully replicate.

Installation

Windows

Make sure Ruby is installed on your computer. If you don't have it, get RubyInstaller before installing Sass (Sass is compiled with Ruby).

Mac

If you're on a Mac, you don't need to install Ruby—it comes pre-installed.

Install Sass

Once Ruby is installed, open Terminal (Mac) or cmd (Windows) and run the install command.

cmd:

gem install sass

Terminal:

sudo gem install sass

Verify (returns the current Sass version):

sass -v

Preprocessing

How to start

We need two stylesheets for this tutorial—one .css and one .scss. We'll call them style.css and style.scss, both inside a folder named app. Run:

sass --watch app/style.scss:app/style.css

The sass command compiles Sass to CSS. With this command, the input (app/style.scss) is compiled to the output (app/style.css). Sass will watch the input for changes and recompile automatically.

Examples

Variables

In Sass, you can store values in variables ($) and reuse them across the entire stylesheet.

compiles to:

Mixins

Mixins are one of my favorite Sass features. Writing vendor prefixes for every property is tedious; with @mixin, you can write them once and reuse them everywhere. Here's how I use it for opacity:

We can pass values with $ to make the mixin flexible.

compiles to:

Functions

We can use @function in Sass. In the example below I use a function to convert px to rem (and vice versa). When working with rem, you should provide a fallback because rem is not supported in older IE browsers. Browsers that support rem use rem; the rest fall back to px. You can also use operators like +, -, *, /, and % in Sass:

compiles to:

Nesting

With Sass you can nest CSS rules like HTML, giving your styles a clearer visual hierarchy—more readable, organized, and clearer.

compiles to:

Takeaway

I hope you enjoyed this short tutorial on Sass. Sass makes CSS easier to maintain, more readable, and reduces tedious work. You can check my GitHub repository to see how I use Sass on this portfolio. To get in touch, visit my LinkedIn or email ghsspower@gmail.com. Thanks!

Title : Beginner's guide to Sass
Date : February 13, 2018
Writer : Hyouk Seo (Spemer)