30 August 2011

The Sass way

Yesterday I started using Sass/SCSS to compile my style sheets in preparation for Rails 3.1 which is due out August 30th (today). It’s safe to say it’ll be my default way of writing CSS when possible from now on. The code is just so elegant and really is the way CSS should be. Nesting and re-using code is made simple and logical as I’ll illustrate later on.

At first I was a bit sceptical, thinking “why would I want 2 style sheets in my project?” but then I actually started converting an existing sheet to SCSS and already, the difference reason is clear. My style sheet of 1000+ lines was condensed down because of mixins and nesting and I set up my colour variables at the top of the stylesheet so any changes I make will flow straight through to the rest of the site.

Here are some examples to illustrate it’s awesomeness:

.nav{
  border-bottom:1px solid #666;

  li{
    float:left;

      a{
        color:#fff;
      }
  }
}

Which is the same as:

.nav{ border-bottom:1px solid #666; }
.nav li{ float:left; }
.nav li a{ color:#fff; }

And that’s pretty cool, but what about reusing code? That’s where mixins & variables come in

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

Which can be used like so:

.info-box{
  border:1px solid #111;
  background:#EEEDDD;
  @include border-radius(5px); //outputs the mixin code replacing $radius with 5px
}

There are also a few functions available such as:

  • darken(colour, percent) and lighten(colour, percent) which will darken/lighten the colour passed in by a certain %
  • opacity functions to make an element more/less opaque
  • even mixing colours!
  • a full list can be found in the SASS documentation here

So, if that has given you a little insight and you’d like to check it out, which I highly encourage, you can follow the instructions on the Sass site to get started.

Thanks for reading. -Dan