Articles, Tutorials

CSS the right way with Sass preprocessor

Sass is awessome. Since our first date, I’ve been (ab)using her in all the projects. She gives you superhuman abilities, far beyond the reach of what classical CSS has to offer. Sadly, she can’t be found in many WordPress themes and I don’t understand why. Is she not hot enough for the majority of WordPress developers? Perhaps she too complicated for them. Luckily for you, my dear readers, I’ve lived with her long enough to experience all her quirks and me being a friendly fella, I’m going to share them with you.

sass-logo

Alright, enough fun, let’s get serious. Ever wondered how it’s possible that some front-end developers are that exceptionally fast and always smiling? In today’s article, I’m going to teach you their secret weapons. We’re going to talk about Sass, the most popular CSS preprocessor; what, why and how. Don’t worry too much, I assure you Sass is quite easy to understand and learn to use. If you have some CSS skills, you’ll find Sass straightforward to get hold of.

Sass in brief

Sass1, like PHP or JavaScript, is a programming language. The only difference between those is that after writing Sass code, we need to compile or translate the code into CSS because browsers don’t understand it. The compilation is done automatically just by issuing a command or clicking a button. The Sass language is surprisingly similar to standard CSS. Maybe that’s why it has become so popular among expert web programmers. We can almost say that it’s a superset of CSS as it includes all its features and a lot more.

Many people, upon hearing about Sass for the first time, are discouraged from using it only due to the compilation step, throwing away one of the best things that have happened in the CSS space for a long time. Trust me, overcome this obstacle and you won’t even think about returning back to the standard CSS.

Sass features CSS lacks

As Sass is a compiled language, it is based on the same principles as CSS — don’t expect some magic. However, it simplifies the creation of stylesheets while reducing its development time.

Variables

Ever happened to you that you had to put the same color (in HEX #) at two places in the stylesheet file and then, when you decided to change the colors, had to manually change them at both of them? And the time when you used the same color at 10 different places in 2000+ lines long CSS file with the same problem? “What would I give for the ability to have variables in the CSS file”, you sighed.

Well, Sass has them! We simply define a variable (e.g. a color) and then use it in a CSS property. Here’s a quick example:

$menu: #fff;
$menu-hover: #000;

.menu {
  color: $menu;
}

.menu:hover {
  color: $menu-hover;
}

We can define an unlimited number of variables anywhere in the CSS (Sass) file, the only condition being that they have to be defined before they are used. After compiling the code, variables get removed (CSS doesn’t support them) and their values are used on the places where we put them (e.g. taking the example above: color: $menu becomes color: #fff). More on variables on Sass official docs2.

Mixins

What if we need to use the same CSS code for multiple CSS selectors3. In CSS, we are out of luck and have to duplicate the code. On the other hand, Sass supports so-called “mixins” which do exactly that, behaving similarly to variables: we define a mixin and then include it in CSS selector when needed. Continuing the example above, we want to use CSS3 property border-radius for our CSS selectors. However, as border-radius has to be vendor-prefixed4 in older browsers, we would have to duplicate the prefixes in all selectors. Thanks to Sass mixins, we define a border-radius mixin which will do it for us:

@mixin border-radius($radius: 3px) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  border-radius: $radius;
}

.menu {
  @include border-radius(10px);
}

.footer {
  @include border-radius();
}

After the code is compiled into CSS, the @include mixin statement is replaced with the body of a particular mixin. Avid readers will notice that our mixin — border-radius — accepts one optional parameter $radius. If we supply a value for $radius, it will be used for the border-radius property. If left out, the default value 3px will be used. To read more about Sass mixins and its parameters, visit their docs5.

Nesting

No, it’s not about birds and how they sleep. This is nesting:

// level one
.header {
  // level two
  .menu {
    // level three
    li {
      // level four
    }
  }
}

“aargh, what’s that?! It’s not a valid CSS code!”. Nope, it’s not and that’s the whole point of Sass: it gives us an enormous power over traditional CSS. The above nested Sass code translates to this CSS code during compilation:

.header .menu li {
  
}

What’s nice about nesting is that you can do things like this:

// level one
.header {
  // level two
  color: red;
  .menu {
    // level three
    color: blue;
    li {
      // level four
      color: black;
    }
  }
}

And after compilation to CSS:

.header {
  color: red;
}

.header .menu {
  color: blue;
}

.header .menu li {
  color: black;
}

As you can see, Sass nesting adheres to the DRY (don’t repeat yourself) principle of software development6. No more of that .selector-one .selector-two .selector-three etc craziness.

Proper file imports

Did you know you could import another CSS file from the first one7? Like this:

// style.css

@import url("another-style.css");

There’s one huge issue with CSS’s @import, namely: the second CSS file is not imported on the server but from the client. It means that when your browser is loading the website, parsing (reading) the CSS files and runs into an @import statement, it will make another HTTP request to the site’s server for that CSS file, all the while waiting for the file to load so it can continue with reading its contents — and that’s bad for the site’s performance. You don’t want the site to make unnecessary additional requests to the server because of bandwidth and latency reasons.

What we want to do is to have the CSS imported on the server, so the contents of both CSS files get combined into one, thus saving the additional request. Unfortunately, standard CSS is not capable of doing that. Fortunately, Sass is.

Frameworks

Variables, mixins, imports and other Sass features allows programmers to construct so-called frameworks8, making our life easier, speeding our work and keeping us sane. Compass9, being one of them, was actually how I got to know and use Sass in the first place. I was told to learn “compass” for an upcoming work back then and believe me, when I opened their site, I was completely lost. “What is that compass thing? What is Sass?” Took me a while to understand it so take it easy, no, you are not too old for this — it comes with a steep learning curve.

So, what does Compass do? Well, for example, let’s say that we have a link (anchor) and want to style its coloring. Without Compass, we would have to do something like this:

a.our-link {
  color: black;
}

a.our-link:hover {
  color: blue;
}

a.our-link:visited {
  color: yellow;
}

We have to use three CSS selectors to have the colors for normal, hover and visited links. With Compass, we just make use of their link-colors mixin:

a.our-link {
  @include link-color(black, blue, yellow);
}

Ta da! This is, like, 0.2% of Compass goodies so check it out, please.

Another powerful Sass framework is called Susy10. It is used for custom CSS page layouts, ranging from static to fully responsive and fluid ones. Basically, we can say that it’s a grid system, similar to Twitter Bootstrap. I’m sorry, but I really don’t know how to describe Susy better; for more info, refer to their site.

Additional features

In my web-related projects, 90% of the time, the above mentioned Sass features is all what I need. However, sometimes more advanced ones have to be utilized. Here’s a list of some of them:

  • conditionals (if else)
  • functions (rgba, opacity)
  • referencing parent selectors (&)
  • string interpolation
  • @extending

I recommend going through them; you’ll become a Sass guru by doing so!

How to install Sass

Sass itself is developed in one of the most popular server-side programming languages, Ruby11, so make sure you have that installed first. Then, it’s just about running the

sudo su -c "gem install sass"

command.

Nothing above makes any sense? Do you use Windows and hate command line? I got some good news for you then: Sass can be used from within a standard GUI application. Check them out12.

I have Sass installed, now, how to compile scss into css?

.scss is the file extension for the syntax of Sass language. When styling our site in Sass, we need to transform — or compile — Sass styles into pure CSS. Now that we have Sass installed, we can compile the stylesheets file with this command:

sass --update style.scss:style.css

In case you use Sass in your WordPress theme, from within the command line, navigate to the theme’s root directory and run the above command.

Not using the command line? Those GUI applications I mentioned before will do the trick.

Tips and tricks

Automatic compilation

Instead of compiling Sass styles into CSS, file by file, we can run Sass in a watch mode, meaning it will observe files on disk, automatically compiling them on a change.

Run from JavaScript with gulp/grunt task runners

Instead of running Sass compilation from a command line or a GUI application, it can be run from JavaScript, especially if using Gulp13/Grunt14 task runners for deployment. Both of these utilities have full Sass support. This is my preferred way of using Sass in all my projects.

Blazingly fast compilation with libsass

Let’s get real: Ruby is slow => Sass compiling is slow. Have thousands of lines of Sass styles? Then compiling could take seconds. I read once about a company with a website whose Sass stylesheets compilation took 40 seconds. Imagine making a change and then waiting 40 seconds for it to show. No way!

LibSass15 comes to our rescue. It is a “C/C++ implementation of a Sass compiler”, making Sass compiling 10 to 100 times faster. Take that Ruby! The only downside is that Compass is not yet fully ported to Sass (it is using Ruby code) so it won’t work with LibSass. However, that’s not a big issue: Compass mixins have already been ported to Sass16. They are not complete but better than nothing.

Additional resources

Sass is becoming rather popular among WordPress themes these days, rightfully so. Here’s a list of a few well-known starter themes with Sass support out of the box:

  • Sage17 from the guys at Roots.io
  • Underscores18 from Automattic
  • Make19 from The Theme Foundry

Twitter Bootstrap20 — “the most popular HTML, CSS, and JS framework” — is developed in another popular CSS preprocessor, Less21. The thing is, if we need to override some of Bootstrap’s settings (like colors or grid system), we can either use their web interface22 (which I don’t like) or install Less, modify its variables and recompile. However, as I don’t like and use Less as well, I’d appreciate a Bootstrap port in Sass. Well, there is one — the official one!23.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s