Organizing your SASS/Compass files using partialsPosted on: April 06, 2013

This may not be anything new, but it's really handy and I thought worth sharing for those that haven't come across it yet.

When developing your CSS, there are really handy ways/techniques you can adopt to organize your code:

  • Separating sections using good old fashioned comment blocks:

    /_===== BEGIN homepage =====_/
    .foo {
    color:blue;
    }
    /_===== END homepage =====_/
  • In SASS/Compass, you can have a section containing all your variables:

    $mainColour: blue;
    $spacing: 10px;
  • Likewise for all your mixins:

    @mixin knockout($_img) {
    background:url($\_img) no-repeat;
    display:block;
    height:image-height($_img);
    overflow:hidden;
    text-indent:-9000em;
    width:image-width($\_img);
    }
    // Found here: http://css-tricks.com/redesigning-with-sass/
    @mixin hoverActiveFocus($property, $value) {
    &:hover, &:active, &:focus {
    	#{$property}: $value;
    }
    }

My way of doing this before used to be to simply have one SCSS file, with compass includes at the top (@import "compass/css3"; anyone?), followed by variables, then mixins, then my code separated by comment blocks.

Enter SASS/Compass partials

See the SASS documentation for this here, but basically, what I ended up doing was splitting out the above three points into their own files: _vars.scss, _mixins.scss, and _homepage.scss (adding a new file for each section I add). Why the underscore prefix? That just tells SASS/Compass not to compile that file so that you don't have unused compiled CSS files lying around. Now I would just have one main.scss file, and the contents would look as follows:

@import "vars";
@import "mixins";
@import "homepage";

Notice that when importing the partials, you drop the _.

Adding the styling for a new section/page is really easy as well. Just create a new partial file, and be sure to add the @import to the main file and off you go.

Now when SASS/Compass compiles, you will get a single main.css file which you can then include in your pages. Happy days!

A word of caution

As mentioned by @gryghostvisuals on twitter: