Matthew Stopa | Inline Style Sheets with HAML

Inline Style Sheets with HAML


December 03, 2011


HAML is in my opinion the greatest innovation in front end web development of the last 5 years. It really gets down to the essence of what HTML is trying to say, just without all the hoop jumping. It's certainly made my life a lot easier, even though 70% of what I do is backend development.

Generally using inline styles with HTML isn't a good practice. You should have a separation of concerns (as much as reasonably possible) between how the page is structured and the styles it has. When I'm working on small utility websites for myself I don't like switching back and forth between 2 files when I want to make changes to the style, so I'll use inline styles, at least temporarily in my app.

With HTML that's pretty easy, all you would do is this:

That wasn't as easy as with HAML though. At first I was trying things like this:

%div.my_class{ :style => { :background => "#00000" } }

That unfortunately did NOT work. It took a little tinkering but I eventually realized that you just need to pass it in as a string. Which at first seemed counter-intuitive but I realized how much easier that made things. Here's how that code should look:

  %div.my_class{ :style => "background: #00000" }

Inline style sheets are useful for some small testing but definitely be sure to clean that up before it goes in a project. Even 'throw away' apps have a tendency to stick around a long time or change into something bigger, so even if you do commit things like this, make it a priority to move them into their own .css file as soon as you find you have a real need for the app.