Every developer who has done bit of web programming is familiar with CSS. A language that enables adding style to a web page, but quite limited. Through this article, we will try to understand why, and above all, we will discuss a more efficient alternative: CSS preprocessors
Preprocessors: from long and complicated code to a maintainable and organized code
As you must know, CSS allows you to style a webpage, but you might have noticed that for styling only one element you need to write a lot of code. This code can quickly become disorganized, difficult to read and thus hard to maintain. It is due to CSS lacking variables and functions that other programming languages possess, forcing you to repeat yourself. Not DRY-friendly (ed. Don’t Repeat Yourself) at all!
CSS evolves constantly and new methods are invented to write more efficient CSS code. Among all these advanced methods, we will mainly focus on CSS preprocessors.
What is a preprocessor?
To put it simply, a preprocessor allows you to write CSS in an alternative language (don’t worry, it’s very close to native CSS) bringing advanced features like variables, functions and the possibility of including files. In short, a lot of things allowing you to write more simply, to better organize your code, while avoiding repeats as much as possible.
Once the CSS code is written in this new language, it will be compiled to be transformed back to native CSS, the only one that web browsers can understand. This is something very important to know about preprocessors: they bring new ways to write code via an alternative language, but ultimately the code sent to the browser remains native CSS. Preprocessors do not bring new features to CSS, but make it more efficient.
Here’s a small diagram to summarize how SCSS works:
Among the most common CSS preprocessors, you’ll find Less, Stylus, but you will mainly hear about Sass / Scss.
Code-wise, what is the difference?
Here are some examples highlighting the interest of using CSS preprocessors:
With CSS you would write:
Instead, with SCSS you would write:
Not bad right?
An example now with defining mixin (SCSS functions),
with CSS you would write the following:
With SCSS, you would write:
Here’s what’s interesting about it all, rather than repeating the style several times for different text, we use mixin specifying certain parameters.
Now you know what a CSS preprocessor is, and how to use it.
I’m not going to go into details of each step today but I will make sure to do so in a future article.
See you soon 🙂