Using Compass and Sass for CSS in your Next Project
Sass could potentially be called CSS 2.0; it has some really nifty features that allow you to write your code in less time and with more flexibility. In today’s article, we will be working the basics!
What is Sass?
Sass is simply a different way to work with CSS. It allows you to keep your CSS code very simple and helps increase readability. It takes something like this:

And turns it into:

You can check out Sass at http://sass-lang.com/
What is Compass?
Compass makes working with Sass even easier. The author, Chris Eppstein, has also included some converted frameworks such as Blueprint, YUI, and 960.gs. It also easily integrates with Ruby based projects, but is just as easy to add to any other project. Compass is open-source and is extremely well documented. Check out the source and documentation.

Installation
Both Sass (which is part of the Haml Project) and Compass are installed through RubyGems. If you dont have any clue what I am talking about, check out "Step 1 – Installing Ruby on Rails" of my previous article Ruby on Rails for Designers, and follow the steps down until you hit the section named "Installing Rails".
To install both of these gems, we can just run a single command:
(sudo) gem install haml chriseppstein-compass

As long as it says that it successfully installed both gems, you are good to go!
Project Setup
If you are working with a Ruby-based project then check out the documentation as it will explain how to get it working with your specific framework, but I’ll assume we are working with a simple HTML or the like project.
The compass command has a lot of options, and if you run compass –help, you might see:

FYI: The next to top line that says "Loading haml-edge gem." is because I use the latest version, so you don’t need to worry about it if yours says something different.
Now we are going to start our Compass project. To create run the following command (including the trailing period, that tells compass where we want to make our project!)
compass --sass-dir=sass .
And you should see:

Where initializing, Compass would normally default to having the Sass in a folder name src, but I wanted to change that so I added the option. If you look at the folder, you should see a file named config.rb and two other folders.

The config.rb is the configuration that Compass looks at, but most of the time you wont need to mess with this. Also, like the output from the creation command says, we have three ways of updating our CSS from our Sass:
compass – using this option, you would have to be in the correct directory, and then Compass would compile your Sass once.compass -u path/to/project – this is about the same as the command as above, but you do not have to be in the project directory, and rather pass in it with the command.compass --watch [path/to/project] – this command is pretty awesome in that it watches for any changes to your Sass files and will automatically recompile them whenever a change is detected.Now that you know how to setup a project, I’ll explain some of the "rules" of working with Sass
Sass Syntax
Normally when writing CSS, you would write something like:
#header {width: 900px; background:#111;}
#header a {color:#000; text-decoration:none;}
One of the problems with that is that you are repeating the same name many times. Lets make this into Sass. I am going to be working in the screen.sass file, so delete everything and your Sass would like:
#header
:width 900px
:background #111
a
:color #000
:text-decoration none

Personally, that it much easier to read and write this way, no curly braces or semicolons. The way that Sass understand the nesting is through indentation.
The first selector is not indented at all so the final CSS with start with that. Also, all properties, (so color, height width, etc) begin with a colon. So for the properties for #header they are indented. It does not matter if you use tabs or spaces, but you must remain consistent, otherwise you will see an error (which I’ll show in just a minute).
So now that you have your properties, we have our next selector. Since this is indented to the same as the properties, the CSS output will be #header a ...
Now that we are this far, lets try compiling: (in your project directory)
compass

And voila!

Let’s say that you didn’t indent everything the same, Compass would error:

Now, once you know CSS, Sass wont be very much of a learning curve, as the main difference when getting started is the different formatting rules. Next, we will get working with some of the more advanced (but cooler!) parts of Sass.
Features of Sass
Variables
One awesome feature of Sass is it’s ability to use variables. An example:
!link_color = #fff
#header
:width 900px
:background #111
a
:color = !link_color
:text-decoration none
Compiling this, would give you:

Math
You may be laughing at this title, but its true, you can do math in Sass! For this demonstration, we will be using Sass’s interactive mode, so run:
sass -i
And a little messing around would give you:

Or a more visual approach:
#111 – #999 = #000
#111 + #999 = #aaa
#398191 + #111 = #4a92a2
#398191 – #111 = #287080
Apart from addition and subtraction, you can also multiply and divide:
#398191 / 2 = #1c4048
#398191 * 2 = #72ffff
To exit the Sass interactive mode, keypress Control-C, and then type "end", and press enter.
Mixins
If you have ever heard of keeping your code DRY, DRY means "don't repeat yourself." Mixins allow you to do just that. For example, with the gaining popularity of rounded corners, you may want to create a mixin to handle that, so somewhere, (not under a selector) you would add:
=rounded :border-radius 4px :-moz-border-radius 4px :-webkit-border-radius 4px
And to use, you would do something like:
#header :width 900px :background #111 +rounded
And when compiled:

Lets say though, you may want the border radius to be variable – well you can have a mixin expect to be passed some values. Changing our mixin, it would look like:
=rounded(!radius = 4px) :border-radius = !radius :-moz-border-radius = !radius :-webkit-border-radius = !radius
And then to use you could use what we did before, and then the value would default to 4px, otherwise:
#header :width 900px :background #111 +rounded(8px)
Importing
Sass also has the ability to import other Sass files, so lets say you wanted to import a file (in the same as this sass file), you would add:
@import reset.sass
This feature is really nice in giving you the ability the keep extraneous styles outside your main file. For example, you could also keep a mixins sass file that you copied around projects and then a simple import would add that code it – no copy and paste.
Conclusion
I hope you understand the basics of using Sass and Compass and will possibly use it in your next project! Now, if you are like I was when I found Sass, and said "I don’t need this!", give it a try. I’ve switched over to it for all of my recent projects and I really enjoy working with it.
Links
Here are a few links that may help you along the way:
- The Sass Reference contains what I talked about today and much much more. Definitely worth a look if you are serious about Sass.
- The TextMate bundle for Sass is great and I use it often.
- The official screencast for Compass, while long, covers about every base with Compass and Sass.
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.


Nice tutorial, thanks for your effort. It is always good to know that there are other ways of doing things, however it seems to me that it is always better to keep it simple. This method reminds me of the “microsoft” way of doing things, making them more complicated than they ought to be!
Comments like this remind me of an old guy I met while I was working in an electronics workshop placement during university. This guy couldn’t understand why we were learning to program in C. In “his day” everything could be done in assembly code. There wasn’t a problem that couldn’t be solved by getting down and dirty with the 1′s and 0′s.
html and css are the assembly language of presentation. They are what the machine understands. They don’t have to be what the human writes. I realized that CSS was broken when I found there was no mixin support. There was no way to create a CSS style that was a combination of some other styles. Sure you could do that in the HTML by adding multiple CSS styles to an element but then you have broken the separation between presentation and data.
I can understand Juan’s concern, and I too have been very resistant at the idea of introducing a new tool. But the sad reality is the nature of what applications require these days (web or any other platforms) have made simplicity a prehistoric commodity. I like the parallel you draw here between this and assembly language vs C, very well put. Maybe small and personal projects could be the excuse to really leverage these tools before moving them into our personal workflows. My 2 cents.
Positively
Cool thanks for the tut
never heard of this before. Gonna try it out tomorrow, thx
Ok i updated my mind *g*
I used it now a while ( 1 whole day :) ) and i have to say its very nice.
With -watch you can let it watch your .sass file and on any change ( when you save again the file ) it will compile it automagicly.
Fail.
Having variables in CSS would be definetly nice, but I really don’t see how this method would be viable in real world (TM). Adding one more complex solution in the boiling pot doesnt help, if CSS is pulp of an ID-mess anyway.
“The commentors who don’t see the use in something like SASS probably have not worked on large web projects before.”
Yeah, that must be it. Or could it be that the “solution” is worse than the original problem…
if you’ve every worked on a project with 1000+ lines of CSS code you can really appreciate how setting global variable for colors, margins, and other common elements can be. it’s the equivalent of using include files in PHP or partials in rails. you change your code once and it updates everything…
Mixins and variables are what really make sass amazing.
Hm…
Awesome tutorial. I am new to CSS and Web Design and nothing can be a more clean way to create stylesheets
Thanks for sharing
omg, this could save so much time, too bad its only for ruby.
It’s not only for ruby, you just need to install ruby and rubygems to pull it down as a gem. You can use it in any project.
Would love to use this but sadly I use VWD to do my websites…
Unless they a version to use with it, I won’t be able to.
Really awesome though. Hopefully someone will come up with an .NET equivalent, if possible.
I defended this when it first popped up on Reddit.
The coolest thing about this is that you can edit multiple regions, in multiple projects, at the exact same time.
For instance, if you wanted to change the background color of your headers and footers in every page on your website, you could.
You can modify all the typography on your site just by modifying one element.
It’s ridiculously awesome and no one seems to grasp it’s potential.
Having difficulty installing it though… :P
“It also easily integrates with Ruby based projects, but is just as easy to add to any other project.”
How do you do that then?
Anton – I discussed how to use it with a project that is not on of the Ruby ones Compass has support for.
“For instance, if you wanted to change the background color of your headers and footers in every page on your website, you could.”
Err… and this cant be done with CSS?
“It’s ridiculously awesome and no one seems to grasp it’s potential.”
I disagree. People dont see the potential, because it isn’t there. I prefer KISS over DRY any day.
Sorry for sounding so negative.
#header, #footer {}
Not sure what CSS can’t do there. I don’t get the point of this article.
Interesting, but won’t be easier write CSS normally? I mean, we are used to write it as it was created. Using Sass could delay our process. Besides, using variable will complicate our life.
I do prefer to write CSS classes and ids than have to make a CSS-based advanced programming.
Guys thanks for all the positive comments.
As for the negative ones….
Yes this is a Ruby based tool, and Ruby is easily installed on just about any system out there.
While some people can write CSS faster than Sass, I have found that I can work with Sass much more efficiently than I could before I started using Sass.
Also, Sass is not a whole new different language. It is simple some rule changes to CSS.
And for the confused….
I based this article for projects that are not based on Ruby so thus wouldn’t have Compass built-in support. The steps are all meant for an environment in any language, and is not tied to any specific language. You do, however, need Ruby to use Sass.
And once you get Sass and Compass installed, working with Sass is extremely simple.
sass is great. with haml, it’s definitely cleaned up code on every project i’ve used it for and made it really easy to modify/update code. i knew it supported variables but wasn’t aware that i could do math with it… for those users w/ css who want to convert you can use css2sass to convert your existing code
its amazing reading the comments how many people just dont get what this is, how it actually works, and how it is beneficial.
maybe the tutorial isnt written that great…
I have loved the idea of compass since seeing it; but am now looking at using csscaffold since I use php more than ruby so for me csscaffold is my preferance over compass (for php users this is a must see).
Once you grasp the power and immediacy that sass provides and compass further enabls you to harness I am sure many will adopt it for regular use.
Its a great concept beacuse you can produce a custmised bespoke css out that is clean by compiling your sass using mixins (patterns) which can be repeated in sequences if need be. You can use a framework and map classes from the framework to your own liking. This way you can get the benefits of using frameworks but without the hassles. Much of the concepts used within sass can (when modfied) be to css (indenting etc — of cource sass nests as well as embeds therefore you have to type less which means fewer typo mistakes)
Seeing the comments above its clear that many don’t see this. Though still in the first foot steps of sass use myself (perhaps Chris or Andrew could clarify / epxand upon what I am trying to convey)
+customise output
+(re)use existing patterns & framworks
+repeat sets of classes etc (typography h1-h6 may be made from a mixin with margins font size altering with each interation)
+use mathmatical expressions
+use contsants so yes you can change #header, #footer bg colour quite easily with css across 1,000s of pages but sass takes this further eg you could use constants and math to alter many such settings within nested sass sheets rules and uses of mixins in your screen.sass or whatever your master project sheet is called — but you could also use sass to create sets of sheets which use & resuse sass to produce css sheets — a web dev could set up a sass libs (mixins & frameworks) from which client work can be styled rapidly
- its adding another part to the process of production
- sass requires strict formating that css does not (messy css is hard to maintain)
- at times you may find that
For those of you who don’t understand the point, I wrote a blog post for you to explain the benefits:
http://chriseppstein.github.com/blog/2009/09/20/why-stylesheet-abstraction-matters/
That article doesn’t highlight anything you can’t do in CSS. Just write better abstracted, object oriented CSS. No compiling necessary.
actually a really inspiring discussion :) first i didn’t get it, now i start to see how it could pay back in time. since it’s abstract in comparison to plain css it needs some thinking in order to be productive for you. i guess once i start using it and start thinking out of the box it could really pay back in time. unless by that time something else shows up… :) but taking a risk also always pays back, one way or another. thanks for the article and the patience
i see its great as long as you started working with it a lot, the first time i used it, it took me a lot of time to write the syntax and to think how to write less. the thing that i need to know, is the compiled css file size good enough for the project performance?
Over the last few hours have installed and trialled compass…. very nice. It’s not until you actually build a significant .sass file to create a .css that you’d require for an average website that you realize how much more concise and maintainable the .sass file is compared to .css.
It’s really easy to go in and make changes to the .sass whereas changing .css usually means finding and changing the same thing in multiple places and crossing your fingers, hoping that you found them all.
I’m having several problems:
related to compass:
“could not find gem chriseppstein-compass locally or in a repository”
gem version is 1.3.5
and i can’t convert a sass file with
“sass style.sass style.css” neither :(
any help welcome
I am having the first problem too.
ERROR: could not find gem chriseppstein-compass locally or in a repository
My gem version is 1.3.6
Running the command ‘gem sources’ gives me:
*** CURRENT SOURCES ***
http://rubygems.org/
ditto
Seems that the files location has changed…
(sudo) gem install compass without the chriseppstein
If you still get this error, you should update ruby (if you haven’t yet installed it) by typing:
gem update –system
you may need super-user privileges to do this and prefixing the sudo command will grant you just that for one line.
sudo gem update –system
NOTE: if like me you get an error that says “You don’t have write permissions[...]” you should go into
your Disk Utility application (assuming you are on a mac) and repair your disk privileges.
Looks like tags aren’t supported in the comments. You should use the command:
(sudo) gem install compass
instead of:
(sudo) gem install chriseppstein-compass
pool of shit
Hi I finaly got it working (newbie to terminal) but when i run this
compass –sass-dir=sass /Users/me/Sites/_htdocs/sass/
it generates this:
exists sass
directory sass/
directory stylesheets/
create config.rb
convert screen.sass
create sass/screen.scss
convert print.sass
create sass/print.scss
convert ie.sass
create sass/ie.scss
exists stylesheets
compile sass/ie.scss
create stylesheets/ie.css
compile sass/print.scss
create stylesheets/print.css
compile sass/screen.scss
create stylesheets/screen.css
When i add code to screen.scss and I compass it it generates an error. If I change the file names .scss to .sass it works fine
any thoughts?
This is because Sass now has two different syntaxes. Oldschool Sass syntax and the more CSS-like Scss syntax. If you add Sass syntax code to a *.scss file (or viceversa) you’re going to get errors. Just make sure you use the file extension of the syntax you’re using.
Regarding this, in my opinion I just don’t get why people asked for a more CSS like syntax. Not having to type the curly brackets or semicolons saves quite a bit of time in the long run, and helps make everything look cleaner.
Great Article :)
Never heard of Compass or Sass before, but it looks like it could save allot of time!
I just wrote an article on my blog (http://bit.ly/aSfZ1y) about learning Sass 3 and its new syntax SCSS. I am really freakin digging it a lot. Compass was a pain to get installed, but once I got it working, it was a breeze.
Is there a cheat sheet for Sass and maybe a cheat sheet for Compass that shows the commands you can use on the command line? The damn help in the command line is a terrible way to read that stuff.
maths on lengths for relative sizing: awesome.
darken / lighten also are excellent for css3 gradients. the best thing is that it is automated, and just changing one color can change a whole gradient completely.
all in all, since the thingy compiles down to css, i agree it does nothing that css alone can’t accomplish (thinking this would be stupid imo) BUT, doing this kind of tricks in css would require more trials and approximation. sure it can be done, but not with the same workflow. for instance, look at the following excerpt (it’s easy enough to understand without knowing sass) and tell me you’d rather attempt to recreate that from scratch in css :
@import ‘compass/css3′;
$base_color: #5291C5;
$button_size: 30px;
.button {
line-height: $button_size;
padding: 0 $button_size/2;
height: $button_size;
@include border-radius($button_size/2);
border: 1px solid darken($base_color, 20%);
@include linear-gradient(color-stops(lighten($base_color, 30%), lighten($base_color, 15%) 4%, $base_color));
&:active {
@include linear-gradient(color-stops(darken($base_color, 30%), darken($base_color, 15%) 4%, darken($base_color, 7%)));
}
}
ps. i much more like the new scss syntax than the one explained in the article
I think the concept that SASS brings to the table (or CSScaffold, for that matter) is one we’ve all had when we play with CSS and think, “Gee, I would be nice if you could use variables and constants here, and if you could duplicate less code.” And then we would think of splitting our CSS up into many little files, since they’re easier to organize by function, only to find that that wasn’t such a hot idea because a browser will have to make a new HTTP connection for each one to download it.
So here’s SASS/CSScaffold adding just those features that CSS was missing. But is it all good news? I’d say on the whole, yes, but here’s a few points:
SASS requires that you compile your stylesheets every time you update them. My typical development cycle is make a little change to CSS (one one monitor) and hit refresh in my browser (other monitor) to see if the change did what I wanted it to do. That would have to change: now I would need to compile my CSS before I hit refresh. Not insurmountable, but it’s one more thing I can and will forgot and then I’ll think, “Hey, now why didn’t that change do anything?” only to find out after some headscratching that I forgot to compile.
CSScaffold doesn’t seem to have this problem: since it’s written in PHP, it’ll run every time the CSS is requested from the server. I’m sure the authors have built in some sort of caching, so it should be quick enough. That actually sounds handier to me than SASS does, merely because I don’t need to compile. So the question is then, is CSScaffold just as good, better, or worse? If it’s just as good, I’ll go with it instead of SASS!
But is what SASS/CSScaffold do really that new? Like I said at the start of this post, it’s an idea all of us have thought of… and implemented! It’s always been possible to produce CSS through PHP. You can put a link to a PHP file in your page’s header, have it output a text/css header and you’re good to go. That’ll allow you to use variables, like SASS, constants, like SASS, functions and mixins, like SASS, all at zero cost since you had PHP anyway. You’ll basically only need to write the fancy gradient functions that SASS adds.
In order to add caching, you could pull your CSS through Smarty, thus prettifying the syntax a bit (it never feels quite right having PHP produce actual HTML or CSS what with the separation of code and presentation, so using Smarty gives a fuzzy warm feeling of righeousness). You could even write some spiffy new functions for Smarty, thus creating your own Sassy Smarty. So why all the hullabaloo?
Well, for one thing… SASS does more than I ever implemented with a CSS/PHP/Smarty approach, so hats off for that. But I still don’t like the compilation requirement.
You don’t have to compile everytime you make an update to the scss file.
You can have compass watch the folder and it will automatically compile on the fly.
The syntax is:
compass watch path/to/folder
Hey, just wrote this css to sass/scss app which might help some of you guys. Check it out:
http://css2sass.heroku.com/
Best\nPablo
great intro article to sass/ compass.
Don’t you mean CSS4?
O.k. for the first part I am a designer….. full time, and for the second part I hate overcomplicated entities…. simpler is better….. And as a designer this is where the compass and sass CSS3 definitions allow a lot less copy and pasting and more fluid code….. Try it you might just be surprised….. I think people that hate it have never tried it, or they have too little command line code experience…..
I’m actually can’t work at all without sass.
I’ve discovered sass months ago and now I would find some difficulties writing pure well done nested css from scratch.
I started using SCSS and I didn’t like the simplified sass syntax, even because I didn’t (and don’t) find it simpliest… we all know how to write a css file; are brachets and semicolons a real waste of time? No, i don’t think so. I’m used to read css code that is familiar for me; and when I see a scss files after several months I can understand it immediatly. And scss has exactly the same features (mixin, variable, math ecc)…
I’m reading this article ’cause many collegues suggested it to me but I can’t understand wich is the addons of compass + sass … what compass does more then sass or scss? maybe I’m missing something…
Hello all,
Did my first slide and dice using Compass (and so SCSS). Wow so easy, so quick !
Will be using compass now on.
nadim attari
mauritius
Plz read “slice and dice” instead of “slide and dice”
Debugging totally sucks. Not having the CSS mapped to a line number in the source is slowing things waaay down for me.
Am I missing something, is there a way to map the rendered css back to the .scss files?
im having with this compass “watch” the project. when I told compass to watch the project that I recently working with but there seem nothing happening. any ideas peep? :/