Getting Sassy
I recently saw on Twitter someone referring to CSS as a Cascading Shit Show. I can’t remember who said it to give credit, but I wish I did, because it’s rather accurate.
I’m of this persuasion as well because with all of my projects, my approach to CSS seems, to me, to be sloppy and all over the place. I try to keep things organized, but it still seems unruly, or at the very least, very cascading.
I decided to dive into Sass, because it clears up these frustrations with CSS by allowing variables, inheritance (nesting and extending), and mixins. To play around with these features, I decided to refactor the style of a small project, My Etsy Map.
Get the Sass
First, if you’re building a Ruby app without Sass pre-compiling (like Rails), you will need to include the sass
gem in your Gemfile. My app here is a Sinatra app, which uses Rack, so not only did I have to include the gem, but in the config.ru
file, I needed to include the sass/plugin/rack
and use the appropriate Middleware (Sass::Plugin::Rack).
Some Sass
To start, I went through and refactored for DRY-ness. I noticed some repeated styles that I could abstract out into variables
:
1 2 |
|
I decided to got even more fancy and incorporate some mixins
, because I had a couple of CSS3 styles that require browser specificity. mixins
work like methods that take in parameters. Then you can call them later with include
, while providing the appropriate value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
I also played around with nesting
, making use of the &
to reference the parent selectors on my a:hover:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
The CSS output of this assigns the .footer
class to the a element and the hover selector styles; this saves me from typing .footer
on all of the elements that have that class, as well as keeps it organized.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Compiling
Compiling Sass into CSS is necessary, as the browser only reads CSS. After I wrote my styles in a Sass file (.scss), I had to Sass-ify it by simply running the sass
command within the root drectory of my project, where your .scss file is turned into a .css file. The sass command takes [options], like the super useful —watch, which as you can guess, watches for changes to your .scss and compiles the .css as the changes are made. But if you just want to simply compile, just include the [input] (.scss) and the [output] (.css) files.
Sass is super fun and coming from Ruby, logically familiar to me. I’m excited to start incorporating it into all of my projects from now on, as it clears up most of the frustrations with CSS.