6 Reasons You Should Use a CSS Preprocessor

CSS Preprocesors

CSS preprocessors are scripting languages that extend the default capabilities of CSS. They enable us to use logic in our CSS code, such as variables, nesting, inheritance, mixins, functions, and mathematical operations. CSS preprocessors make it easy to automate repetitive tasks, reduce the number of errors and code bloat, create reusable code snippets, and ensure backward compatibility.

Each CSS preprocessor has its own syntax that they compile into regular CSS so that browsers can render it on the client side. Currently, the three most popular and stable CSS preprocessors are LESS, Sass, and Stylus, however there are many smaller ones as well. CSS preprocessors all do similar things but in a different way and with their own syntaxes. Each of them has some advanced features unique to them and their own ecosystem (tools, frameworks, libraries) as well.

Personally, I use LESS, as I’ve found it really helpful that I could copy and paste my original CSS into an LESS file and work from there. (LESS can be written just like plain CSS).

1. @variables

Variables make your code easier to maintain by giving you a way to control those values from a single location:

1.1 @nested selectors

Result after compiling:

2. @imports

CSS @import makes another http request to fetch another stylesheet, while a Less @import grabs the content from inside your imported file and includes it within the compiled stylesheet. This means only one http request, allowing you to create partials and organize your css just that little bit better without any downsides!

A normal import will grab the contents of that file and dump it into the file asking for it. Super useful. Concatenating files is a vitally important feature of preprocessors.

A (reference) import doesn’t do that. In fact, it doesn’t put anything at all into the file asking for it. The code in that file is just now ready to use, either by calling a mixin within it or extending a selector within it.

3. @mixins

Mixins copy all of the properties into a selector, which can lead to unnecessary duplication. Therefore you can use extends instead of mixins to move the selector up to the properties you wish to use, which leads to less CSS being generated.

Result after compiling:

4. @extend

Extend is a Less pseudo-class which merges the selector it is put on with ones that match what it references.

Result after compiling:

5. @math

Math functions includes methods which are used for performing numeric operations such as round, square root, power value, modulus, percentage, etc.

Result after compiling:

6. @loops

One of the best things about LESS is that you can do loops and build classes dynamically.

The following example is to make dynamically classes, increments of 10. I could have written 10 classes, but this way is much nicer and easier to maintain.

Result after compiling: