David recently redesigned his blog and is having a series of guests write posts for his site. We decided to do it crossover style: he writes an article for CSS-Tricks and I’ll write an article for the David Walsh blog. He used Sass in his redesign and his article below is about that experience. I’ve been using it for closer to a year, so my post on his site is about that experience.
Creating a website without using a CSS preprocessor seems a horrible decision. Even if only to be able to quickly modify a few colors or element dimensions, or even just to easily merge and compress CSS files, CSS preprocessors are becoming essential. For my recent redesign of the David Walsh Blog, I decided now was the time to dive face-first into CSS preprocessors. Here are a few thoughts about my experience, and hopefully you pick up a few tips along the way.
Deciding to be Sassy
There’s not much a decision to be made about whether or not to use a tool like Sass or LESS, the questions is more of which should be used. In the end, I chose Sass because:
- my experiences with LESS have been … less than appealing; the tool seems … less maintained
- a utility like Compass, a collection of mixins with an updater, is invaluable
- the
extend()
API looked great - embedding media query styles within a selector improves organization
- sprite generation is a huge time-saver
- Chris Coyier told me to!
When you author a blog like David Walsh Blog or CSS-Tricks, learning a new CSS utility also presents the perfect opportunity to write about another useful topic. Using Sass on this project was obviously the best choice.
Useful Snippets
Here are a few of the Sass snippets I used often on my site:
Vendor Prefixing
@mixin vendorize($property, $value) {
-webkit-#{$property}: $value;
-moz-#{$property}: $value;
-ms-#{$property}: $value;
-o-#{$property}: $value;
#{$property}: $value;
}
Float Clearing
@mixin clear() {
&:before, &:after {
content: "\0020";
display: block;
height: 0;
overflow: hidden;
}
&:after {
clear: both;
}
}
Offscreen Text
@mixin linkTextOffscreen() {
text-indent: -9999px;
overflow: hidden;
text-decoration: none;
display: block;
font-size: 0;
text-align: start;
}
:hover, :active, :focus Styles
@mixin hoverActiveFocus($property, $value) {
&:hover, &:active, &:focus {
#{$property}: $value;
}
}
I used these mixins quite a bit throughout my code. A few of my snippets mimic functionality provided by Compass, but I like seeing the specific styles provided by mixins.
Mistakes, Mistakes
As with using any tool for the first time, I made quite a few mistakes. Mistakes are healthy though – you learn from them and write about them so others don’t take those same missteps. Mistakes I made include:
- Nesting == Bloat: The biggest mistake I made with Sass, by far, was nesting styles when they didn’t need to be. At the time of launch, my main CSS file was a vomit-inducing 59k! I’m still working toward reducing the size of my styles, and it’s a much more difficult task now that the site has launched because of…
- …Specificity Clashes: Because of my issue with nesting styles when I didn’t need to, I ran into a bunch of specificity clashes, bloating my CSS file even further. When it got to the screen size media query CSS, I was needing to mark everything as !important. That’s an incredible amount of CSS bloat and hassle because of improperly using SASS selector nesting.
- Sprite Generation… Too Late: One of the big reasons I chose SASS was because I knew SASS managed sprite generation. What a time-saver, right? Well, only as long as you knew how to format them in the first place. My problem was that I created my CSS with normal background-image declarations, without paying attention to SASS’ desired format. I went to create my sprites after knowing the correct format and said “WTF FML”. In the end, I created my own sprites because I didn’t write my SASS correctly in the first place. Very annoying mistake.
- Duplicating Compass-provided Helpers: I don’t need to cite them… I’m more than certain I duplicated functionality provided by Compass. I’ll likely pay for it later if I don’t update my code and stay aware of browser capabilities.
Tips and Last Impressions
I want to leave everyone with a few tips for getting started with SASS, and share a few last impressions of Sass development:
- Despite my duplication of Sass-provided functionality and nesting issues, Sass is an incredible tool that, accompanied by Compass, provides the ultimate tool+updating environment available.
- When nesting selectors, ask yourself if it’s really necessary to do so. Sure nesting also allows for better code organization, but a bloated stylesheet makes all of your users suffer.
- Create variables for your CSS animation properties, especially duration and delay. Consistent animation timing ensures eye-pleasing UI effects.
- Create variables for block padding, and use simple equations ($blockPadding/2) for lessor blocks. This ensures consistent element spacing.
- You can nest media queries for selectors but I prefer creating a separate file for mobile / media query-specific styles; it allows me to see the entire set of mobile styles in one glance. The same could be said for my print styles.
- I used these directions to add Sass syntax highlighting to Sublime Text 2.
- Keep track of your CSS file size(s) while you code, and periodically review your nesting strategy to avoid style bloat.
- Utilize CSS animations as best you can — they can save you a load of JavaScript code down the road.
In the end, I’m incredibly happy with my decision to use Sass as my CSS preprocessor. The documentation is helpful, you can get up and running in a few minutes, and Compass is an invaluable tool in so many ways. My only problems with Sass were self-inflicted and will be easily avoidable the next time around. Give Sass a chance for your next website or redesign – its usefulness is immeasurable and will pay off for the duration of your project.
I use Sublime Text 2 as my editor, and find this is a great plugin: http://wbond.net/sublime_packages/prefixr
It saves you prefixing things which you don’t need to prefix, it could reduce extra bloat.
Chris talks about using Compass to add the prefixes – is prefixr better, more up to date? i.e. is there a reason to go the prefixr route than Compass which is already installed with SASS?
Prefixr has proven to be useful to me, but yeah, if you just use a preprocessor like SASS or LESS, you can just make a few mixins; prefixr isn’t necessarily needed, unless you are choosing not to use these. You don’t even need to rewrite the mixins either (the joy of copy/paste).
Prefixr is great, but when you’re working in a .scss file, you can be working with
vs
The one has far greater benefits in neatness than the other.
Great stuff. One challenge I’m still facing is working with a team / clients that may need to maintain the CSS afterwards as well. Still haven’t had the chance to commit a project to a 100% SASS solution.
Great post!
My original obsession with nesting definitely bloated my CSS… wish I could have read these warnings before I started getting sassy.
Instead of your version of vendorize, I use:
which has the advantage you can use it like this
too (you could even use multiple properties like so:
Excellent Peter! I’m going to … borrow … that! :D
Compass has an built-in feature avoid unwanted prefixes… So you don’t have to write your own custom mixins ;)
http://compass-style.org/help/tutorials/exclude_vendor_prefixes/
A little improved one:
The overall redesign is nice. I have 1 problem with it though. When I hold down on the down arrow to scroll, once I let go, it scrolls back up to each next blog post. Bad for UX in my opinion!
Would it make more sense to use @extends for float clearing and text invisibility?
David… Looked at your new blog and read Chris’ article then tried to leave you a comment – and your link doesn’t work. Tried to leave a bug report – but not going to register with git just to tell you of a bug you may find out about eventually. So, perhaps you’ll view these comments.
like the new skin to your site – one thing I’ve noticed. When viewed in narrow size (ie mobile) this post (Chris’) in particular shows only the title for quite a long scroll. ?possibly a media query to decrease heading tag font size might look nice? Just a thought.
With the
hoverActiveFocus
mixin, you’ll end up with a lot of code bloat if you’re need multiple rules, as SASS doesn’t yet group equivalent selectors. Instead, you just try replacing the rule statement with an@content
statement. Learn More@DavidWalsh instead of the current linkTextOffscreen() mixin that you’re using, take a look at this updated version of image replacement.
Ran across it when using Bones (a WordPress HTML5 starter theme), also highly recommended.
Take a look at the last comment on the updated version of image replacement article that you posted and you’ll see exactly why you shouldn’t use that as a work around to the -9999px solution.
Hmmm. This emperor does have clothes, but they are pretty shabby raiments with respect to integration
For example:
(1) the world’s most useful debug feature Firebug doesn’t know anything about SCSS file numbers (… I know … there are some kludgy plugins that help a bit etc etc) making debugging css with firebug virtually useless
(2) almost all of the universe’s best IDE’s have pretty good code coloring and code completion for css, but appear to know zilch about SCSS or LESS (sure … early days … plugins coming blah blah)
(3) preprocessors for css, hmm. perhaps javascript pre-compilers next, what a mess.
Perhaps it always was like this – standards developing too slowly, hacky work-rounds, better standards, repeat… ah well .
True that, my mayor culprit with using CSS Preprocessors as well. It almost turned me away in the beginning, but after a while it’s not so bad. I prettify the compiled CSS and paste it into the browser when I’m debugging. From there it’s easy(er) to find the corresponding row in my LESS/SASS.
Not entirely true! WebStorm have quite decent support and more is coming. Pair that with CodeKit and you have a pretty sweet setup!
Hopefully Source Maps will make it into CSS as well (we have them in JS – linking the minified/obfuscated file with the source), then all this issues will go away.
1.) Firesass
2.) ST2 with SCSS plugin (takes 10seconds to install)
If you’re too lazy to do this, then you’re going to have a hard time with Sass… otherwise it will ease your life tremendously (of course, in the end it’s up to you, but at least don’t just reinforce clichés)
Lol regular CSS is just easier, neater, no need to bloat your style sheets. Ridiculous to learn sass or less unless your in business coding websites full time.. Ridiculous
@nick – why else would you use CSS unless you were building sites full time? As a hobby? Yes then maybe a preprocessor is a bit over the top. Most people in here are discussing what isn’t a hobby.
a lot of us, doing it full time, aren’t bothering either.
the funny bit is people using it to shave a few kilobytes off their CSS file…complete lunacy.
From a maintenance perspective, nesting media queries is a killer feature. Couldn’t you have sass compile those queries to a separate file? Seems like a perfect fit for a preprocessor.
@David – Any particular reason your not using the “fix” for offscreen text from the HTML5 Boilerplate? iPad 1 (for one) have issues with placing stuff way off the page.
/* Hide only visually, but have it available for screenreaders: h5bp.com/v */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }
hoverActiveFocus can be written with @content:
I’m glad that more and more people start to utilize SASS.
However I have two notes about your article:
I think that the snippet “Vendor Prefixing” is a bit over the top. Nowadays only very, very few properties need the whole slew of prefixes anymore. Since Firefox doesn’t need them for animations, transitions and transformations and IE10 uses almost everything unprefixed (and WebKit will surely follow soon), there is no need for such an enormous snippet in my eyes.
And since you mention the embedding of media queries: Don’t do (or suggest) that, because that would be a true reason for code bloat. Imagine if you nest every the media query for every property/element directly beneath it. Attaching all the media queries together at the end of the CSS is still the best way, until SASS automates that for us.
How do you cope with older versions of browsers then?
You don’t really expect everyone of your visitors to have the latest version do you?
Sure you could have a separate stylesheet for each browser and version, but that doesn’t seem any cleaner to me – au contraire…
SASS wont be able to group media queries together at the end of the CSS files as this will play havoc with the specificity of the selectors.
As Chris Coyer pointed out in a recent episode of Shop Talk Show, GZIPing your files will deal with all the repetition caused by having embedded media queries. Its also better in terms of code organisation as you can see all the styling for one element, regardless of the media query.
I just took the plunge, installed Code Kit and started using a preprocessor on my latest project.
My only question is, on the SASS website they refer to SASS & SCSS. To me it appears that SCSS is the latest versions of SASS. When you refer to SASS are you talking about SCSS?
@sebastian – sass & scss are the same thing. They are just written differently :)
Not really the same things then. Different syntax.
Was just curious if people use the SASS syntax or SCSS syntax.
There is better way for generic prefixes: example. This allow to set correct prefixes by properties. For example,
border-radius
never has-o-
prefix.Just a quick thought of mine – You may want to convert your clear @mixin into a %placeholder, to reduce duplicate lines of code. Using such is as simple as a @mixin:
“@extend clear;”
Fixed typo:
“@extend %clear;”
Nesting too deep = troublesome specificity. Yep–I’ve learned that the hard way, too!
I’ve always been interested in pre-processors but have never really tried them out. After reading this I think it’s convinced me to finally give it a go!
Sass is any day a far better tool because it is easy to use. Plus Compass is a great collector of mixins.
I have used Sass for a couple of projects and my biggest disappointment is that nested selectors use the descendant combinator (E F) instead of the child combinator (E > F).
I rarely use descendant combinators so I end up using “& > F” everywhere.
Oh and have you seen http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/ for offscreen text?
Just begin your nested selector by
>
,~
or+
and that’s it.should output:
I’ve used it a lot with LESS and per http://stackoverflow.com/questions/7345763/sass-and-combined-child-selector it should work the same way in SASS.
Offscreen text > this method is probably a bit better (I didn’t test it yet) but see Paul Irish comment about it.
About 8 months ago I considered SASS, saw the word “ruby” then went with LESS and WinLess. That was probably a silly decision. One thing that always bothered me with LESS is how slow it was, in combination with WinLess, to build a .css file.
LESS development had been dormant for months (stuck at v1.3.0) and the github folks with 100+ issues were getting restless and talking about spinning it off with the developer’s blessing. I eventually jumped on the SASS/Compass train, and it’s better. LESS was actually just updated yesterday (Oct 18) on github, but I ain’t going back. On a PC, you can use the command line to auto-build your files.
Two tips I didn’t see mentioned:
1) On Windows, if you use command line “compass watch” in combination with a “config.rb” file to watch and automatically build your files, it’ll open up a command line dialog box. You have to keep it open all the time, which is annoying. I use “HideIt” to hide it in the tray area:
http://vasanrulez.deviantart.com/art/HideIt-Hide-all-your-windows-206517834
2) Compass has one killer function called “inline-image()”:
http://compass-style.org/reference/compass/helpers/inline-data/
What this does is allow you to base64 encode your images directly in the stylesheet instead of referencing files on the server. Saves in downloads, helps your Yslow/Page Speed scores (if you’re into that sorta thing), and acts as a nice way to cache bust your images, since you’re not actually serving any real file-based images.
If you use this technique, it will bloat your CSS something awful. Gzipping won’t really compress the Base64 stuff, so be sure to optimize your images before “inlining” them. Finally, if you care about IE7 (as many sites still have to cater to this demographic), you’ll have to feed the real image file to it as it doesn’t understand Base64. Something like:
Non-preprocessor CSS is crazy talk. LESS is a nice thought. SASS+Compass is genius. Thanks David.
I have been using Sass for about a year, having neater code helps you write better CSS IMO. Would not go back now
Having used LESS before it hasn’t really inspired me to move away from the traditional CSS techniques. Sass however looks good may convert me :)
Compass has tons of CSS3 helpers that you just have to import and then to use you do
@include border-radius(5px, 5px);
and it outputs all of the vendor prefixes. They also have other helpers built in like vertical rhythm to keep your font looking consistent. I know Compass also has a built in CSS Grid framework but I recently used Susy which is created by Eric Meyer and is a responsive grid framework I’ve loved using it and felt it was very easy to pickup on.
I’ve used both less and sass before. I think currently sass has more options but less is not that bad. I know it compiles for me quickly and I found learning less to be easier mainly because their documentation was better. I hope someone picks up the torch for less soon and continues the work but its something that can still be used. People have been bashing on it a lot lately and almost seems like its the in thing to do.
As for an earlier comment about only saving a few seconds when compared to css thats really not true. You save minutes which turn into hours down the road. Ever since I made the switch my workflow has increased greatly.
Chris, can you write an article about Sass + Compass best practices as I’m currently facing the same issues.
I’m developing a small website and the CSS file size is HUGE (~40KB and I’m just starting)
Heya, I’m still relatively new to SASS so I might be missing something here but was wondering why you are use mixin for clearfix rather than extend?
In the output, mixin basically repeats the clearfix code on the class you’re using it on whereas extend just adds the class to the code; resulting in less “bloat”. Also the clearfix code isn’t likely to change.
Thanks!
Hi Chris,
Great article about SASS,
I’ve a query in css file edit, after making sass file, it compile css file, If I edit in css file in middle than again start work on sass file, now it will overwrite my edits in css, is there any way to ignore this.
Please let me know if there it is.
Sincerely,
Mufaddal
Mufaddal, if you’re using something to automatically compile your SASS to CSS, such as Scout or a “compass watch” .bat file, then, NO, there’s no way to override the overwrite of your .CSS.
It seems you’re thinking of SASS/CSS like they should be synchronized forward and backward. The writing is only one way: SASS to CSS. But that’s the point of using SASS. You shouldn’t be diving into your raw .CSS file ever again–You should only be editing your .SASS file(s) henceforth.
Now, if you must have this disabled, then you’ll have to turn off whatever is polling .SASS file changes, and then run the compiler manually.
But just know, by doing this you can open yourself up to inconsistencies.
@Mufaddal:
I am thinking “_partials” and then just use plain css – cause css is also valid scss. So all your additional css will be imported to the compiled main css. Give “partials” a read and it might be a way to go for your needs.
I know my comment is running late, but maybe helpful for the gentle reader and common stumble uponer.