Coming from the Rails world, I’m pretty much spoiled when it comes to writing CSS: with tools like Sass/SCSS and the godsent Compass framework, it’s been ages since I last had to write a line of CSS directly.
With the new look of our website out, it was time to give our blog a facelift as well. We had been using WordPress before, which worked really well, so instead of looking for any other solutions I decided to just create a new theme for it, but it soon became apparent that writing the CSS by hand was not going to cut it. Luckily for me, Sass and Compass provide some very nice tools to use them outside of Ruby-based projects. All you need to install them (assuming you have Ruby installed) is to run:
$ gem install compass
I based my theme off of the default WordPress theme, Twenty Eleven. As any other WP theme, this one has a main stylesheet named style.css. The first thing to do then was convert this file to Sass format, which was a piece of cake using sass-convert. I decided to put my source Sass files inside a subfolder named sass:
$ cd my-wordpress-theme
$ mkdir sass
$ sass-convert style.css sass/style.sass
Or, if you prefer SCSS, just replace sass/style.sass with sass/style.scss.
The next step was to test the new Sass-based stylesheet. The first thing to do was to remove the original CSS file, although it’s a better idea to keep it around, so I just renamed it:
$ mv style.css style.css.old
In order to test our new Sass-based stylesheet I used the sass tool:
$ sass sass/style.sass style.css
At this point I loaded my theme in WordPress and everything was looking dandy. The next thing I wanted to do was to be able to use the Compass goodness in my stylesheets, so I created a Compass config file using the compass config command:
By default this creates a config file in config/compass.rb. The parameters I used are:
- --sass-dir sass — Specifies that I’ll be storing my .sass files in the sass subfolder.
- --css-dir "" — This tells Compass to compile CSSs into the project root.
- --relative-assets — This enables relative asset paths, so if I use helpers like image-url in my stylesheets (which you should) Compass will compile those paths relative to the CSS, which is what WordPress expects.
With that done I could now start using compass watch to get my stylesheets compiled automatically on each save, which is a must during development:
$ compass watch .
# >>> Compass is watching for changes. Press Ctrl-C to Stop.
With that running all I had to do is edit the sass/style.sass file, and all changes were automatically applied to the CSS. Just remember to run it each time you start working on your stylesheets.
Now all that was left was to actually include Compass in my stylesheet to be able to use its mixins and helpers, so I edited sass/style.sass and added at the top, right after the WordPress meta-data:
And that’s it. Now you can enjoy all the benefits of using Sass & Compass in your WordPress theme. Please leave a comment if you found this useful!