8 Tips to Help You Get the Best out of Sass

Cathy Dutton
Tweet

Sass creates Syntactically Awesome Style sheets, or at least thats what it is supposed to do.

When used effectively, Sass helps to build scalable and DRY CSS. When used incorrectly however, Sass can actually increase file size and add unnecessary or duplicate code.

Below is a series of hints and tips to help you get the best out of Sass…

1. Structure Your Sass

Getting your site structure correct from the beginning is vital for any new Sass project. Using partials allows you to break the CSS up into smaller more manageable blocks of code that are easier to maintain and develop.

Partial files are created using an underscore and are not output as separate CSS files. Each partial should be imported using a master Sass file (global.scss) in the root of the Sass folder.

For example, here’s a sample folder structure to demonstrate this:

vendor/
base/
|
|-- _variables.scss
|-- _mixins.scss
|-- _placeholders.scss

framework/
modules/
global.scss

This folder structure ensures the site is easy to work with, and add to. For example, new modules can easily be added to the module folder and then added to global.scss using @import.

To demonstrate, here’s a sample global.scss file:

/* VENDOR - Default fall-backs and external files.
========================================================================== */

@import 'vendor/_normalize.scss';


/* BASE - Base Variable file along with starting point Mixins and Placeholders.
========================================================================== */

@import 'base/_variables.scss';
@import 'base/_mixins.scss';
@import 'base/_placeholders.scss';


/* FRAMEWORK - Structure and layout files.
========================================================================== */

@import 'framework/_grid.scss';
@import 'framework/_breakpoints.scss';
@import 'framework/_layout.scss';


/* MODULES - Re-usable site elements.
========================================================================== */ 

@import 'modules/_buttons.scss';
@import 'modules/_lists.scss';
@import 'modules/_tabs.scss';

And as a side point, you might want to check out Hugo’s extensive post on Sass architecture for more tips in this area.

2. Use Sass Variables More Effectively

Variables are one of the more straightforward features of Sass but are still on occasion used incorrectly. Creating a site-wide naming convention is essential when working with Variables. Without one, they become harder to understand and re-use.

Here are some tips for creating useful variables:

  • Don’t be to vague when naming your Variables.
  • Have and stick to a naming convention (Modular, BEM, etc.)
  • Ensure the variable use is justified.

Here are some good examples:

$orange: #ffa600; 
$grey: #f3f3f3; 
$blue: #82d2e5;

$link-primary: $orange;
$link-secondary: $blue;
$link-tertiary: $grey;

$radius-button: 5px;
$radius-tab: 5px;

And some bad examples:

$link: #ffa600;
$listStyle: none;
$radius: 5px;

3. Reduce Mixin Usage

A mixin is a great way to include sections of code multiple times within a site. However, including a mixin is the same as copying and pasting the styles throughout the CSS file. It creates a mass of duplicate code and can bloat your CSS file.

A mixin therefore should only be used if an argument is present, to quickly create modified styles.

Here’s an example:

@mixin rounded-corner($arc) {
    -moz-border-radius: $arc;
    -webkit-border-radius: $arc;
    border-radius: $arc;  
}

This rounded-corner mixin can be used in any situation simply by changing the value of $arc, making it a worthwhile mixin:

.tab-button {
     @include rounded-corner(5px); 
}

.cta-button {
     @include rounded-corner(8px); 
}

A bad example might look like this:

@mixin cta-button {
    padding: 10px;
    color: #fff;
    background-color: red;
    font-size: 14px;
    width: 150px;
    margin: 5px 0;
    text-align: center;
    display: block;
}

This mixin has no argument and would therefore be better written as a placeholder, which brings us to point 4.

4. Embrace Placeholders

Unlike mixins, placeholders can be used multiple times without adding any duplicate code. This makes them a much friendlier option for outputting DRY CSS:

%bg-image {
    width: 100%;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
}

.image-one {
    @extend %bg-image;
    background-image:url(/img/image-one.jpg");
}

.image-two {
    @extend %bg-image;
    background-image:url(/img/image-two.jpg");
}

And the compiled CSS:

.image-one, .image-two {
    width: 100%;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
}

.image-one {
    background-image:url(/img/image-one.jpg") ;
}

.image-two {
    background-image:url(/img/image-two.jpg") ;
}

The repeated code in the placeholder is output only once with only the unique styles being applied to the individual selectors. If unused, the placeholder styles are not output at all.

Tying in with point 3, placeholders can be used alongside mixins to reduce duplicate code and still keep the flexibility of a mixin…

/* PLACEHOLDER 
============================================= */

%btn {
    padding: 10px;
    color:#fff;
    curser: pointer;
    border: none;
    shadow: none;
    font-size: 14px;
    width: 150px;
    margin: 5px 0;
    text-align: center;
    display: block;
}

/* BUTTON MIXIN 
============================================= */

@mixin  btn-background($btn-background) {
    @extend %btn;
    background-color: $btn-background;
    &:hover {
        background-color: lighten($btn-background,10%);
    }
}

/* BUTTONS
============================================= */

.cta-btn {
    @include btn-background(green);
}

.main-btn {
    @include btn-background(orange);
}

.info-btn {
    @include btn-background(blue);
}

5. Use Functions for Calculations

Functions are used to perform calculations. A Sass function does not output any CSS. Instead, it returns a value that can be used in the CSS. This is useful for calculations that will be made throughout the site.

For example, functions are useful for calculating the percentage width of a given element:

@function calculate-width ($col-span) {
    @return 100% / $col-span 
}

.span-two {
    width: calculate-width(2); // spans 2 columns, width = 50%
}

.span-three {
    width: calculate-width(3); // spans 3 columns, width = 33.3%
}

6. Order Your Work

Place all mixins, functions, placeholders and variables in their relevant partial file. Keeping blocks of code together will ensure they are easy to edit and reuse in the future.

Site-wide elements should be kept together in a base folder. The base folder should contain global variables such as fonts and colour schemes:

$font-primary: 'Roboto', sans-serif; 
$font-secondary: Arial, Helvetica, sans-serif;

$color-primary: $orange;
$color-secondary: $blue;
$color-tertiary: $grey;

Module-specific mixins, functions, and variables should be kept within the correct module’s partial file:

$tab-radius: 5px;
$tab-color: $grey;

7. Limit Nesting

Overusing nested rules in Sass can cause a lot of issues, from complex code to over-specificity and too much reliance on the HTML structure of a page. These things can cause issues further down the line and potentially increase the need for the inclusion of !important, which should generally be avoided.

Here are some golden rules for nesting:

  • Never go more then 3 levels deep.
  • Ensure the CSS output is clean and reusable.
  • Use nesting when it makes sense to, not as a default option.

8. Keep Things Simple

The concluding point I’ll make in this post is to keep things as simple as possible. The purpose of Sass is to write cleaner more manageable CSS. Before creating any new mixins, variables, or functions, ensure that their presence will enhance development and not overcomplicate things. All Sass features are useful when used in the correct situations and in moderation.

Creating an endless list of variables without clear usage, or a complex function that is difficult to understand for anyone other than the author is not the intention and will not aid development or produce DRY CSS.

Conclusion

That’s it for this list of Sass tips. You might not agree with all of these. Sass is still a fairly new technology so we’re continuing to learn new best practices with it. If you have your own suggestions, feel free to offer a comment.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Anth Winter

    This is a great write-up, Cathy. Very well explained. Is there any reason why you give your color variables a value of a variable (in section 6) rather than just a straight hex value?

    I’m thinking $color-primary having a straight hex value would be future proof enough, should it need to change.

    Or would you use $blue, $grey etc elsewhere too?

    • LouisLazaris

      My guess is exactly what you said, that she’d be using those variables elsewhere too. Makes sense I think.

      • http://www.cathydutton.co.uk/ cathy dutton

        Hugo’s explanation is exactly right, the full code example would look like this…

        $orange: #ffa600;
        $blue: #82d2e5;
        $grey: #333;

        $color-primary: $orange;
        $color-secondary: $blue;
        $color-tertiary: $grey;

        • Benoit Adam

          I do not agree about the use of variables to the represent the colors.
          If you use the “$color-primary” in all your sass files, you never see “orange”. The only place where you see “orange” is where you declared your $color-primary, A simple comment would do the trick and you would get rid of one variable par color:

          $color-primary: #ffa600; // orange
          $color-secondary: #82d2e5; // blue
          $color-tertiary: #333; // grey

          In my variables file I don’t use “$color-primary” or “$color-secondary” but “$color-10″, “$color-20″ etc. It has the same meaning but helps to name variations of the colors: the different gradients of “$color-10″ can be named “$color-11″, “$color-12″ and those of “$color-20″ will be “$color-21″, “$color-22″, etc.

          What do you think of this approach?

    • http://hugogiraudel.com/ Hugo Giraudel

      The point is to have both semantic variable names and comprehensible variable names. Think about it: $primary-color tells you nothing about the color itself, but $blue does.

      The problem with using $blue all over the place is that if tomorrow the main color is not a blue anymore but a red or whatever, you have basically destroyed the whole concept of variable since you will ever have to:
      – Change the variable color, and end up with a $blue holding a redish value
      – Search and replace all the $blue to $red or whatever which completely defeats the purpose

      This is the perfect solution to get the most of both worlds: you still have semantic names (e.g. $primary-color), and variable names that makes sense (e.g. $red instead of #ff0000).

      • Anth Winter

        That’s a good point about having the variables named the actual color, I see now.

        I guess you would then have the option of adding of removing the $blue variable, seen as though its replaced by $red. Or, just build up your Sass file of coloured variable names to use as you need.

      • LouisLazaris

        Of course, “color: #ff0000″ is the same as “color: red” in pure CSS… :)

    • laracraftmili

      Start working at home with Google! It’s by-far the>>CLICK NEXT TAB FOR MORE INFO AND HELP

  • http://dada.theblogbowl.in/ Shaumik Daityari

    Great article, some of them are obvious but some are really new to me! :)

  • Alim Bolar

    i tried using the placeholder in an _variabile.scss and used the @extend in _main.scss file and imported both into global.scss… but this would not work.. however it worked if the placeholder was in the _main.scss file (the same file where the @extend was used) … is this the expected behaviour? Or am I missing something? I would assume like how I can place all variables in a separate file I would be able to keep all placeholders too in a separate file..

    • http://www.cathydutton.co.uk/ cathy dutton

      It could be a problem with the order the files are imported into the global.scss file? The placeholder file would need to be above Main for the @extend to work…

      @import ‘_variables.scss';
      @import _placeholders.scss';
      @import ‘_main.scss';

      • Alim Bolar

        No.. I checked..:-(.. The placeholder files were the first in the series of files being imported.. Anyway thanks for getting back..
        Will try something else.. but I am glad you responded so that now I know it’s not the expected behaviour atleast..;-).. so I can place my placeholders and my variables in a separate .scss file and access them in another as long as the files which hold the variables and the placeholders precede the one that access the variables and placeholders.. right?

  • http://www.technbuzz.com/ Samiullah Khan

    If I’ve code like this and let’s assume .facebook is here a module

    .facebook{

    @extend %fontSettings;
    .section_text{
    padding-top: 250px;
    img{
    width: 38px;
    height: 38px;
    margin-top: 2px;
    }
    }
    figure{
    .play-btn{
    margin:-65.5px 0 0 -30.5px;
    }
    }
    }

    Where should I write code If I want to target .facebook specifically not it’s child? Should I write in the beginning or at the end?

  • http://tihid.com/ Mutebi Roy

    Nice article