August 28th 2011 — Topic: — Topic: CSS

For more on Sass, read The Sass Way and follow @TheSassWay on Twitter.

Note: Throughout this post, when I say “Sass” I mean “Sass and Compass.”

This is not a post saying…

“If you’re still building websites without Sass, you’re doing it wrong.”

This is a post saying:

“If you haven’t tried Sass/Compass, please do before dismissing it.”

My Lawn…



Clint Eastwood in Gran Torino

If you are anything like me, then as a designer you are also probably a bit of a curmudgeon, though perhaps you consider it perfectionism – and justifiably so. You have honed a specific workflow you adhere to because that is what works, dang it. Woe unto anyone who suggests you are not doing things in the best possible way, right? Yes, exactly! Except, well… no.

I believe my first reaction to Wynn Netherland, when he told me I ought to try Sass and that perhaps I would see a boost in productivity, was something along the lines of: “Bah, get off my lawn” — a reference to the cantankerous character played by Clint Eastwood in Gran Torino.

I came to realize that his suggestion was not a subtle way of saying “I know something you don’t know” (though he did), but more of a friendly nudge towards greater efficiency. He was just being a good neighbor, so to speak.

So, I am writing this post in an attempt to get designers out there (who are also already CSS savvy) to try Sass and Compass. I aim for this to be the article I wish I had read when I was first contemplating Sass but (at the time) did not consider it worthwhile. I could not have been more wrong.

FUD

There seem to be a number of false assumptions that designers get hung up on when it comes to the topic of CSS preprocessors. I know such misconceptions exist because I myself had these doubts ruminating in the back of my mind, and have seen others express similar sentiment, without actually having tried Sass. I hope to clear some of those up here…

Myth:

Using the command-line is hard Using the command-line is inconvenient I must learn both Sass and Compass Sass requires me to know Ruby Sass requires a foreign syntax Sass only works in Ruby on Rails Sass is always white-space sensitive

Fact:

Using the command-line is not scary Using the command-line is infrequent Sass and Compass go hand-in-hand Sass doesn’t require Ruby knowledge Sass is just CSS syntax, with extras Sass runs on Ruby (already on OS X)

— outputs flat CSS , to use anywhere Sass itself is white-space sensitive

— SCSS is not, use either one

Think of it this way… As a designer you have undoubtedly worked on some project using PHP, Django, Rails, etc. You do realize PHP is a recursive acronym that means PHP: Hypertext Preprocessor — don’t you? Somehow, it is perfectly fine to preprocess HTML for productivity gains. Why should CSS be off the table?

Setup

Windows:

On Windows, you will first need to run the Ruby Installer.

Linux:

On Linux, Rails Ready provides several Ruby essentials – read more here.

OS X:

This “just works” on a Mac, because Ruby is installed by default on OS X.

Gem Install

Note: The ~ symbol is an alias to username on OS X and Linux. If using Windows, replace ~ with %USERPROFILE% in the following command-line examples.

For the sake of brevity, and server language agnosticism, let’s say you want to use Sass on a flat-file HTML site. To install Compass, which comes with Sass, just open up your favorite command-line utility, such as Terminal.app and type…

Windows:

gem install compass

Linux + OS X:

sudo gem install compass

Next… Actually, that’s it! Compass and Sass are now installed.

New Project

Still got Terminal open? Good, just a few more minor things to type.

To create a SCSS project named “my_project” on your desktop, do this…

compass create ~/desktop/my_project

Or, to create a Sass project named “my_project” on your desktop, type…

compass create ~/desktop/my_project -x sass

Regardless if you specified Sass (or defaulted to SCSS) as your preferred syntax, you will see a directory named “my_project” on your desktop, with a config.rb file inside. Really, this is all you need to get a Compass project going. You will see the various options nicely explained in the “#” comments.

config.rb file:

# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" css_dir = "stylesheets" sass_dir = "sass" images_dir = "images" javascripts_dir = "javascripts" # You can select your preferred output style # here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via # compass helper functions. Uncomment: # relative_assets = true # To disable debugging comments that display the # original location of your selectors. Uncomment: # line_comments = false preferred_syntax = :sass

Now that you’re done creating the project, you won’t need to type “compass create” again until you want to create an entirely new project. Or, if you’re like me – you can tweak your newly created project files and save them to reuse later as starting point for new projects. After which, all you’ll have to do is…

Compass Watch

Now that the “my_project” directory exists, go into it…

cd ~/desktop/my_project

Then tell Compass to watch for changes to your *.sass (or *.scss) files…

compass watch

As changes are detected in your *.sass (or *.scss), new *.css file(s) will be compiled on-the-fly. Once you’re satisfied with how things have shaped up, you can hit Ctrl-C to stop the watcher, and go deploy your flat CSS.

Syntax

You can use either the Sass or SCSS syntax, and can even have *.sass files and *.scss files in the same project, as long as you don’t mix the syntax within the same file. You can also @import flat *.css files into a *.sass or *.scss file. It all compiles down nicely into flat *.css file(s).

Sass and SCSS differ only in that SCSS syntax is a “super-set” of CSS3 — just a fancy term that means all regular CSS still works fine inside of SCSS — and curly braces and semi-colons are still valid and required.

Whereas in a Sass file, curly braces and semi-colons are not only unnecessary, they’re invalid. That might sound like crazy talk at first glance, but after having tried both, I can say I greatly prefer Sass to SCSS. But to each his/her own.

At it’s core, Sass syntax can be thought of as simply CSS without { , } , or ; . In fact, if you do a find-and-replace, substituting nothingness for those characters “”, you’ll be all set to start converting flat CSS files into Sass.

By way of example, here is the same code in SCSS and Sass, and what it would look like compiled (or written long-hand) in CSS…

SCSS:

// This comment is not output to CSS. /* This comment is output to CSS */ #foo { font: { size: 13px; family: 'Helvetica Neue', Arial, sans-serif; } .bar, .baz { border-width: 1px; } .bar { border: { style: solid; color: #369; } } .baz { border: { style: dotted; color: #693; } } }

Sass:

// This comment is not output to CSS. /* This comment is output to CSS */ #foo font: size: 13px family: 'Helvetica Neue', Arial, sans-serif .bar, .baz border-width: 1px .bar border: style: solid color: #369 .baz border: style: dotted color: #693

CSS:

/* This comment is output to CSS */ /* line 5, ../sass/screen.sass */ #foo { font-size: 13px; font-family: "Helvetica Neue", Arial, sans-serif; } /* line 10, ../sass/screen.sass */ #foo .bar, #foo .baz { border-width: 1px; } /* line 14, ../sass/screen.sass */ #foo .bar { border-style: solid; border-color: #336699; } /* line 19, ../sass/screen.sass */ #foo .baz { border-style: dotted; border-color: #669933; }

Compression

You’ll note in the example above that the line numbers for each selector are written out in the CSS file, via comments. This is helpful if you combining multiple files via Sass importing, because unlike the typical @import in a flat CSS file, Sass will combine multiple files into one. This style of commenting helps you trace the origin of a style, in case you wanted to debug.

When deploying to production once everything is solid, there is little need for these comments (nor indentation and line breaks), because browsers will render the code with or without them. Thankfully, all it takes is setting one option in your config.rb file, and everything will be minified auto-magically…

output_style = :compressed

This yields code that is difficult to read for humans, but is perfectly optimized to save precious bytes, and is perfectly parsable by any given browser…

#foo{font-size:13px;font-family:"Helvetica Neue",Arial,sans-serif}#foo .bar,#foo .baz{border-width:1px}#foo .bar{border-style:solid;border-color:#369}#foo .baz{border-style:dotted;border-color:#693}

You’ll even notice that every instance of “;}” has been replaced with “}” because CSS does not require a semi-colon on the last rule of each block. Little things like this add up, potentially resulting in a significant reduction of overall file-size. This equates to faster page loading, which we all know is pretty important.

Compass

Even if the aforementioned features were all Sass was capable of, it would be worth looking into. At the risk of sounding like an infomercial salesman… But wait, there’s more! Where Sass left off, Compass goes to the next level.



Chris Evans as Captain America

Gradients

How many times have you attempted to remember the puzzling syntax for a CSS3 gradient? Though similar in implementation, the code to produce it is maddeningly different depending on the browser.

This is where Compass truly shines, providing mixins that output this code for you. With Sass, most of it you write yourself, but Compass is great at bleeding edge CSS3, for which no human should have to remember the syntax.

This terse, logical Sass/Compass code:

@import compass/css3 #foo +background(linear-gradient(#fff, #ccc))

Turns into this ridiculous assortment:

/* line 3, ../sass/screen.sass */ #foo { background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #ffffff), color-stop(100%, #cccccc)); background: -webkit-linear-gradient(#ffffff, #cccccc); background: -moz-linear-gradient(#ffffff, #cccccc); background: -o-linear-gradient(#ffffff, #cccccc); background: -ms-linear-gradient(#ffffff, #cccccc); background: linear-gradient(#ffffff, #cccccc); }

Experimental SVG

You can even set an “experimental” flag, to have Compass output SVG for you. This is great for browsers like IE9 and older versions of Opera, that understand how to render an embedded base64 encoded image, but can’t natively draw CSS3 gradients. A simple variable set to “true” outputs the necessary code.

If you set $experimental-support-for-svg: true …

@import compass/css3 $experimental-support-for-svg: true #foo +background(linear-gradient(#fff, #ccc))

A base64 encoded SVG string is output…

/* line 5, ../sass/screen.sass */ #foo { background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjUwJSIgeTE9IjAlIiB4Mj0iNTAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIvPjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iI2NjY2NjYyIvPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjZ3JhZCkiIC8+PC9zdmc+IA=='); background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #ffffff), color-stop(100%, #cccccc)); background: -webkit-linear-gradient(#ffffff, #cccccc); background: -moz-linear-gradient(#ffffff, #cccccc); background: -o-linear-gradient(#ffffff, #cccccc); background: -ms-linear-gradient(#ffffff, #cccccc); background: linear-gradient(#ffffff, #cccccc); }

This can potentially add file-size and as such is (smartly) an opt-in feature, because the $experimental-support-for-svg flag defaults to false unless you specifically enable it. Still, it’s pretty cool to know it’s there.

Border Radius

Without belaboring the point of how cool Compass is, let me show one more CSS3 example. Adding a border radius is trivial enough, since the syntax is somewhat similar (aside from vendor prefixes), but what if you only wanted to round three out of the four corners of an element? It gets a bit more tricky, because browsers differ: “…top-right-radius” vs. “…radius-topright” etc. Compass to the rescue!

You just type this…

@import compass/css3 #foo +border-top-left-radius(4px) +border-top-right-radius(4px) +border-bottom-left-radius(4px)

Compass does the heavy lifting…

/* line 3, ../sass/screen.sass */ #foo { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -o-border-top-left-radius: 4px; -ms-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -o-border-top-right-radius: 4px; -ms-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -o-border-bottom-left-radius: 4px; -ms-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }

The Hard Sell

What’s that, champ? You have all that fancy CSS3 syntax memorized already? Right… I bet you do. Keep telling yourself that. Seriously though, even if you know all those keystrokes, who in their right mind wants to type all that?

Okay, fine. I will up the ante. Compass also has support for image sprites. You know that PSD or PNG file you maintain with tons of little icons, where you cleverly count the number of pixels each is offset from the top-left of the document? You can quit doing that, and instead have multiple, separate files that Compass will combine into one single HTTP request.

Sass also has a slew of color functions that can act upon colors, so that you don’t have to painstakingly recolor things in Photoshop, and retrieve hex values via the color dropper. If you want to darken something 10%, just do it…

#foo color: darken(#369, 10%)

Which yields…

/* line 1, ../sass/screen.sass */ #foo { color: #264c73; }

Oh, and get this… Sass supports math, and Compass adds enumeration. That means you can create loops that spit out numerically incremented code, perfect for making custom vertical grid dimensions. For example, the 960 plugin.

There is even a plugin to establish a baseline horizontal grid, called vertical rhythm, allowing you to achieve the (oft sought, rarely realized) goal of uniform line-height throughout an entire page. It’s not automatic, but it certainly gets you further than you might get manually adjusting margin and padding.

Apps

Currently, there are two apps that can be used to basically simulate “compass watch” to check for changes to *.sass and/or *.scss files and convert them to CSS. Also, I know of at least one other app that’s in progress, currently undergoing a private beta test. The two apps available today are:

Compass.app

— built in: JRuby

— open source, on GitHub

— cost: $7.00 compiled



— built in: JRuby — open source, on GitHub — cost: $7.00 compiled Scout

— built in: JRuby + Adobe AIR

— open source, on GitHub

— cost: free

Done

I could go on and on, but instead I will let you go read more about Sass and Compass in detail. I will say this: If you are a designer who prides yourself on writing efficient front-end code, then I would encourage you to give ‘em a shot. Worst case scenario, you end up back writing CSS the way you have been doing it. Best case scenario, you have another skill to add to the ol’ arsenal.

Just think of Sass (and Compass) like the “jQuery of CSS.” Those who understand the fundamentals of CSS will always have an edge over designers who don’t code at all. A solid tool like Compass in the hands of a master CSS craftsman only serves to make him/her all the more effective, further widening the gap.