What are CSS pre-processors and why should I be using one?

What are CSS pre-processors and why should I be using one?

CSS preprocessors, which include SASS, LESS and Stylus, among others, have been gaining a great deal of popularity and rightly so. First and foremost, they inject a great deal of expressive power into your plain old CSS by adding a great deal of dynamism to your code. With the use of the a CSS preprocessor your code becomes more efficient and manageable because it introduces actual programming paradigms into your stylesheets. You can nest rules, concatenate many different files together, declare variables, add conditionals and use loops when building out your stylesheets.

The use of a variable is extraordinarily powerful because you if you want to, for example, change the value of a color that is present in your website you can structure your code so that it requires a single change and recompile your CSS. Another great example is changing a font. I set all of my typographical information (font size, font weight, etc.) in a typography file which, among other attributes contains a variable for my heading and paragraph font family. Should I want to change the font, I simply make a change in my variable file and recompile my CSS. This basically applies the DRY (Don’t Repeat Yourself) principle to your CSS.

With these languages you are also able to do mathematical calculations in your CSS. I can’t tell you how many times I have pulled out a calculator to find the exact pixel width I would need for a given element and now I just plug the formula right into my CSS.

Another very powerful feature is that you also can use conditional statements in your CSS, such as the following, note this uses SASS syntax.

p {
 @if $theme == "dark" {
 color: #000000;
 } else if $theme == "light" {
 color: #EEEEEE;
 }

The way that these work are, you write your code in a specific file format, depending on the preprocessor, and then use a tool to compile the code. Tools can include Grunt, Gulp, command line tools, codekit and more. You simply pass your file, in whatever format (LESS, SASS, Stylus, etc.) and it creates a generated CSS file.

I know you are likely thinking “great another language that I now need to learn”. I felt the same way but to be honest the syntax for all of these preprocessors is very familiar (providing you have been doing some developing). The learning curve was extremely flat and it was totally worth the time because what you gain is indispensable. Here at StatenWeb we have been successfully employing the use of CSS pre-processors to make our development process quicker and deliver flexible solutions for our clients.