CSS Preprocessors and why we can’t live without them

So you’re a developer who usually writes CSS and you’re sick and tired of writing things like this:

.container .class a { color: red; }
.container .class h2 { color: blue; }
.container .class p { color: yellow; }
.container .class .another-class { color: green; }

By the end of the article you’ll be asking yourself: “What could’ve I done with all the time I’ve wasted writing CSS?”

What’s a CSS Preprocessor anyway?

A CSS Preprocessor extends the CSS language by adding features that will make your life so much easier. The code will be more maintainable, easier to read and faster to type (well, not faster but you’ll certainly type less).

If you do a quick Google search for “CSS Preprocessor” you’ll probably come across: Sass/SCSS, LESS or Stylus.
All of them, more or less, serve the same purpose with some small variations. You’ll have to choose one, lucky for you there’s no right or wrong choice.

All the code you write with this new syntax will have to be compiled into normal CSS. What great about it is that we can set minification and compression with the same process (we all know how #perfmatters).

How to have fun while writing CSS

At TBSCG we use Sass when we need to bring out the big guns. With that said, CSS Preprocessors aren’t usually used when you need to do a small change in an existing project using regular CSS. Once again it’s up to you, if you think you’re going to edit this on a daily basis perhaps you should consider creating a .scss file. One cool thing is that SCSS syntax is superset of CSS so you can actually paste regular CSS into a SCSS file and compile it. It won’t be any different but then you could use SCSS syntax for the new pieces of code.

The wait is over, what are those features I’ve been talking about?

Variables

We can create our own variables. Yes, like in a “normal” programming language. We usually create a specific file where we write all our variables so we can easily keep a track of them.

$global-font-family: Helvetica, sans-serif;
$main-color: #333;

body {
  font-family: $global-font-family;
  color: $main-color;
}

You’re welcome! And there’s more where that came from.

@import, let’s keep it clean

I’ve mentioned different files, it’s a good practice to separate your components SCSS into different files. It will be easier to maintain and it’s great for collaboration. Don’t worry, all those files will only generate one CSS compiled file.

You could have your main.scss with this:

@import "components/header";

Which will be fed from components/header.scss

Nesting

Using the example from the beginning of the article we could’ve written it like this:

.container {

    .class {

        a {
            color: red;
        }

        h2 {
            color: blue;
        }

        p {
            color: yellow;
        }

        .another-class {
            color: green;
        }
    }
}

Once compiled it’d look like so:

.container .class a{ color: red; }
.container .class h2{ color: blue; }
.container .class p{ color: yellow; }
.container .class .another-class{ color: green; }

Nesting allows us to save a lot of writing. You have to be carefull though, with this feature it’s easy to overdo creating too many selectors and children. Sometimes a root level class will be more than enough.

Functions and Mixins

So yes, we can create our own functions. Like you would expect, this functions accept parameters and will help you reuse code and write less.

They can do anything you want, i.e. change string to int:

@function parseInt($n) {
  @return $n / ($n * 0 + 1);
}

We can call functions like normal function, ie.:

.class {
  line-height: parseInt(3.5px);
}

Which once compiled will look like:

.class { line-height: 3.5; }

There are also some “special” functions called mixins, we can use them with the @include directive.

@mixin opacity($opacity) {
  opacity: $opacity;
  // IE8 filter
  $opacity-ie: ($opacity * 100);
  filter: #{alpha(opacity=$opacity-ie)};
}

.element {
    @include opacity(.5);
}

Browser prefixing is a pain, we can ease our agony creating a Mixin:

@mixin translate($x, $y) {
-webkit-transform: translate($x, $y);
  -ms-transform: translate($x, $y);
   -o-transform: translate($x, $y);
      transform: translate($x, $y);
}

.element {
    @include translate(200px, 300px);
}

Mixins can also be used without any parameter. Let’s say we need to do some calculations or set styles, something we’ll be using over and over:

@mixin center-block() {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.element {
    @include center-block();
}

Mixins can have default content so it can be easily used to extend/wrap some piece of code, i.e. keep all breakpoints in one place and easily maintain them:

@mixin breakpoint($name) {
  @if $name == very-small {
    @media only screen and (max-width: 29.95em) { @content; }
  }
  @else if $name == tablet {
    @media only screen and (min-width: 30em) { @content; }
  }
  ...
}

@include breakpoint(very-small) {
  .sth {
    font-weight: 700;
  }
}

There’s even more

Each language comes with a long list of core functions such as darken() or lighten(), with this two functions we can change the colors using percentatges:

.class{
    color: darken($main-color, 20%);
}

This is great to create themes from two or three base colors. Designers get onboard!

If the core functions aren’t enough for you and you need more power, check out Compass. I’ll just quote the description:

Compass is an open-source CSS authoring framework which uses the Sass stylesheet language to make writing stylesheets powerful and easy.

My recommendation would be to first to get a sense of Sass and then take a look at Compass.

I’m sold, how do I compile this things?

If you’re friends with the command line it’s probably the fastest way to get you up and running. If you prefer a GUI there’s also Windows and Mac clients to deal with this files. Check out each language site for their How to Install guides.

Final thoughts

At this point I hope you’re convinced of the power of the CSS-Preprocessors. Like anything in the dev world you’ll have to learn it first, there’s no way around it. As you have already seen it’s not hard and the benefits you get from it are great.
In the end this tools help us be more efficient with our work and allow us to optimize our time.

What about you, do you already use a CSS Preprocessor?

Resources to get you started

Share

Published by

Ricard Torres

Ricard is a Senior UI/UX Developer @ TBSCG. Based in Barcelona he also plays guitar, takes photographs and teaches Haidong Gumdo.

6 thoughts on “CSS Preprocessors and why we can’t live without them”

Comments are closed.