22 August 2014

Adding a bit of Sass

Its been around for a while, but i’ve decided to share with you why I use Sass in projects. So what is Sass. Well sass is a CSS (Cascading Style Sheet) pre-processor that allows you to build and maintain complex css files, especially for larger projects…


Its been around for a while, but i’ve decided to share with you why I use Sass in projects.

So what is Sass. Well sass is a CSS (Cascading Style Sheet) pre-processor that allows you to build and maintain complex css files, especially for larger projects. To describe it in a simplistic way, it allows you to develop your stylesheets in a more flexible way.

“Sass is the most mature, stable, and powerful professional grade CSS extension language in the world.”
The clever people at Sass

Sass is generally used and run via the command line. I’m not going to cover the installation of Sass as it not the scope of this blog. However, instructions for setup can be found here http://sass-lang.com/install.

Sass is easy to read and fast to code

#page-info{
  width: 246px;
  float: right;
  height: 470px;

  h1{
    line-height: 30px;
    text-transform: none;
  }

  p{
    margin-left: 20px;

    a{
      color: #333;
      border-bottom: 1px solid #333;
    }
  }
}

The above is taken straight from a current project I’m working on and demonstrates the power and clean way that sass is written. As you can see, each child level is nested inside its parent. Its good practice to try and go no more than three levels deep, otherwise your styles will become too specific (see specificty) and you’ll lose the flexibility you’re adding. This is a guideline only and is suggested to help maintain code legibility.  The above code will then create the following CSS:

#page-info {
  width: 246px;
  float: right;
  height: 470px;
}
#page-info h1 {
  line-height: 30px;
  text-transform: none;
}
#page-info p {
  margin-left: 20px;
}
#page-info p a{
  color: #333;
  border-bottom: 1px solid #333;
}

This my not seem like much of a difference, but it’s less repetitive due to Sass’s nesting syntax structure (we didn’t have to add the #page-info selector) and can save loads of precious time in the long run, making those tight deadlines a bit easier to meet.

Inheritance

Another neat feature of sass is Inheritance. This is enabling selectors to inherit from other existing css classes, this saves you from having to write duplicate code. For example, say we have three buttons that are all the same height, width, border-radius etc, but have different background colours you could easily do the following:

a.button{
  width: 207px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  display: block;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  color: $white;
  font-size: em(18px);
  text-transform: uppercase;
}
#red-button {
  @extend a.button;
  background-color: $red;
  border: 1px solid $dark_red;
}
#yellow-button {
  @extend a.button;
  background-color: $yellow;
  border: 1px solid $dark_yellow;
}
#blue-button {
  @extend a.button;
  background-color: $blue;
  border: 1px solid $dark_blue;
}

Above, we are using Sass’s @extend directive which enables you to include another class or id’s styles. So above the #red-button selector is inheriting all the styles from a.button. This feature means that a block of CSS can be stored in a single CSS class, or id, and then inherited multiple times throughout a style sheet by including @extend, followed by the class/id you wish to inherit.

Better organise your code

One of the things that makes Sass a friendlier way of maintaining your code is by using Partials. With partials you can have for example, a main file that can inherit others.

@import "mixins";
@import "colors";
@import "typography";
@import "main";

The above is an example snippet of the way I personally like to have my main file laid out (notice the lack of file extensions). So my main file takes in sections that hold styling for my typography, colours and mixins. I’ll talk about mixins shortly. All of these imports then combine to make up the final sass file which is then preprocessed to create a single, well formatted CSS file.

So all of this is great, but is it enough to switch to, and start using Sass now?

For me it wasn’t. Deadlines come thick and fast and it’s hard to know when to gamble on learning a new technique. Or even whether or not it will be beneficial to do so in the long run.

I decided to make the switch however, when I heard that with Sass, you could do the following:

Using $variables

The css syntax is easy to write and remember. however, things like hexadecimal numbers for colours, or even a padding/margin values that are sometimes used throughout a project can be hard to remember. We’ve all been there, continuously scroll up and down the page, copying and pasting.

How much simpler would it be if you could store these in variables, either inside a level of nested selectors, where they’d only be defined there, or outside of any nested selectors, where they’d be available everywhere.

// General Colours
$white:    #ffffff;
$black:    #323232;
$dark_red: #c92019;

// Nav text
$light_grey: #c2c2c2;
$dark_grey:  #646464;

// Page Colours
$homepage_color: #fed100;
$cinema_color:   #274d9d;
$play_color:     #f0710a;
$bowling_color:  #00acc8;
$arcade_color:   #d01080;
$golf_color:     #048800;
$eat_color:      #000000;

The above is a glimpse into the color.scss file of the current project I’m working on. Here I am simply storing different colours into easy to remember variables that can be referenced to at a later date like so:

h2{
  color: $white;
  margin: 0 0 0 26px;
}

This might seem like a little thing, but don’t underestimate the power of being able to store css values into well named variables. Especially once you start using mixins.

Mixins you say?

One on Sass’s greatest component, is Mixins…. So what are they?

Mixins are functions containing templates of sass that can be reused throughout a project. The functions can have parameters passed through so that the css generated is unique to the selector using it. To explain a mixin a bit better, here is an example:

// some variables
$avenir_reg: 	"Avenir";
$white:         #ffffff;

// a sample mixin
@mixin fonts($font-types, $color){
  font-family: $font-types, helvetica, arial, serif;
  font-weight: normal;
  color: $color
}

// assigning styles using a mixing
h1{
  @include fonts($avenir_reg, $white);
}

In our example above, the h1 tag is passing through the font “Avenir” and the colour white (already stored in variables $avenir_reg and $white), and passing them through to the Mixin function called fonts() using the @include directive.

From here the styling within that function is added to the H1 tag, along with the correct values added to font-family and colour. This is a very straight forward example to show how Mixins work and would generate the following CSS:

h1{
  font-family: "Avenir", helvetica, arial, serif;
  font-weight: normal;
  color: #ffffff
}

I realise that it takes a lot more code to generate such a little snippet of css, but the above was just an example of how mixins work. The Mixin itself can pass through multiple parameters, and contain any number, lines of code within. It’s the reusable nature of the mixin that can make them powerful.

Recently, I was presented with a problem on a project. I was building a .net mvc5 project and wanted to create a shared layout to be used for four of the views, but I needed to display different colours and background graphics for each view. To target the different views, I added a dynamic class (passed from the controller to the layout using a ViewBag property) to the body of each view (ie. body.home). Then, for each view, I used a layout mixin to style each page with its own graphics and background colour, passing in the values needed for each. Here is the mixin I created:

@mixin page-setup($name, $lines_bg_color, $color, $htag-position){

  background: $lines_bg_color url(../images/#{$main_bg}-bg.png) no-repeat;

  #page-info{
    background: $color center top url(../images/#{$name}-banner.png) no-repeat; 

    h1{ margin: $htag-position; }
  } 

  h3{ color: $color;} 

  hr{ border-top: 10px solid $color;} 

  .white-button{ color: $color; }
}

The above is a small snippet of what I actually used and has been simplified for the purposes of this blog. It accepts four parameters and forms a template that can be reused as many times as needed. In this demonstration, the Mixin is then called by each of the following four pages:

// Targeting classes added dynamically by wordpress

body.home{
   @include page-setup("homepage", $light_red, $homepage_color, 160px 20px 20px 20px);
}

body.event{
   @include page-setup("events", $light_blue, $event_color, 120px 20px 20px 20px);
}

body.location{
   @include page-setup("location", $light_yellow, $location_color, 100px 20px 20px 20px);
}

body.contact{
   @include page-setup("contact", $light_orange, $contact_color, 60px 20px 20px 20px);
}

There’s nothing sass can achieve that css cannot. I could have added the mixin code manually to each of the selectors and not used variables, thus creating long and repetitive css.

With Sass, all the code that would have been repeated if written in CSS, is now contained once, and in one place, making any updates or editing really easy to do.

@Media queries made easy

Responsive websites are a growing trend these days. They need CSS3’s media queries to limit the style sheets’ scope and allow the content to be tailored to a specific range of output devices without having to change the content itself.

I used to separate different screen sizes into huge blocks which i’d have in single media query. I’d write the CSS for mobile first, then have a media query for larger than mobile where i’d write styles for table devices, then styles for website and finally large screen devices. Because of this, my CSS for any element is in at least four different areas on the css file. So many hours wasted scrolling up and down. Now with media queries you can nest them within each selector, making the legibility and time to code much faster.

When developing a responsive website I like to use the following Mixing which I find to be almost invaluable:

// Set media query
@mixin breakpoint($point) {
  @if $point == tablet {
    @media (min-width: 768px) { @content; }
  }
  @else if $point == website {
    @media (min-width: 1080px) { @content; }
  }
  @else if $point == large {
    @media (min-width: 1440px)  { @content; }
  }
}

The above is a powerful function that allows you to set the name and width value of each media query and easily write the code needed for all screen sizes in a very neat and organised fashion like so:

#send-button {

  // mobile style
  background-color: $red;

  @include breakpoint(tablet) {
    background-color: $yellow;
  }

  @include breakpoint(website) {
    background-color: $green;
  }

  @include breakpoint(large) {
    background-color: $orange;
  }
}

As you can see above, the background colour of the button will be red if viewed by a mobile device (notice i’m using the variable $red to hold the hexadecimal colour), yellow on a tablet, green on a website and orange on a large screen device. No more scrolling, easy to read and write syntax as the numbers for each media query are stored in the mixin and can be reused. This is a great way to structure your code and one of the main reasons why I now use Sass when developing all responsive websites.

Functions

This is also a game changer when it comes to css. Functions are similar to Mixins in that they accept parameters. The difference however, is that a function returns a value. I use functions all the time. One of the most used functions is to convert font pixel size into ems:

// Convert pixel to em
@function em($px, $base: $base-font-size) {
    @return ($px / $base) * 1em;
}

h1{font-size: em(23, 16);}

By using the above function, there is no need to calculate what 23 pixels is in ems if the base font size is 16, the function will calculate and return the value, just like a function would return a value in any other language, like php or javascript.

Utility belts for Sass

Finally, to help you along with mixins, functions etc, there are several frameworks available that will help you to do this, for example Compass, Bourban and Susy to name a few.

I personally like and use Compass as it comes with the most features to use, straight out of the box. It does require set up and ruby gems downloaded to work, but once setup, it won’t disappoint.

Conclusion

So I hope by now, you are starting to see the benefits of using Sass to preprocess your CSS code. Its strong, flexible, modular, easily maintained and can cut down the amount of coding needed to write the sometimes mundane and repetitive CSS needed for a project.

Get in touch

Have a project or an idea you'd like to collaborate with Gravity on? Interested in what Gravity can do for you?

Use the form below or email hello@creategravity.com or speak directly to one of our team from one of the numbers below