CSS Preprocessors

What it is

CSS Preprocessors are new styling languages that compile to CSS. You write your code in SASS (for instance) syntax, and then run it through a processor that converts it into vanilla CSS. These languages justify this extra step by offering more powerful features and more expressive syntax than plain old javascript, such as nesting and variables.

Some of the most popular CSS Preprocessors include SASS, LESS and Stylus, in that order.

Why it matters

CSS is an ugly language with some serious limitations. For example, in the CSS for this site, I use the same violet color #700CF4 on many different elements, including links, buttons and icons. That means, I have to write that same string many times across multiple files:

a { color: #700CF4; }
...
button { color: #700CF4; }
...
.atlas__nodes .focused { fill: #700CF4; }

This code duplication is a classic code smell. If I wanted to change this color, I’d need to go through and grep for every instance and change them one by one. To address this, one of the most common features of a good CSS Preprocessor is enabling the use of variables. In SASS, I can write:

$PRIMARY: #700CF4;
...
a { color: $PRIMARY; }
...
button { color: $PRIMARY; }
...
.atlas__nodes .focused { fill: $PRIMARY }

See how this is DRY? Most of the other main features of preprocessors provide, like nesting and mixins, serve this same end.

Interestingly, as more and more of these features are added on, CSS has gotten closer and closer to being a full-on programming language. Indeed, it is turing-complete, so it IS a programming language, albeit a crummy one.

This track of continuously souping up CSS strikes some as odd, since the browser already has a programming language available in Javascript. This has lead to the next evolution after CSS Preprocessors, CSS-in-Javascript as done in React using libraries like Styled-components.

How to learn it

This is personal opinion, but I find that most of the preprocessors are more or less the same. SASS is the most popular currently (11/17), so if I were you I’d learn it before anything else. Obviously, you should understand how to use CSS really well before trying to tack on a preprocessor. Plain CSS is often good enough: remember, YAGNI.

To get started with SASS, it is hard to beat the official tutorials.

Code Academy also offers a free course.