Saturday, May 2, 2009

How to Avoid CSS Hacks

I've decided to use a very tiny bit of javascript to free me of css hacks. I already use js to add a class "jsEnabled" to the <html> element so that I can style things differently if I know that javascript is going to swoop in and alter them later (tabs, carousels, etc). Taking this a step further, I put the browser name + version number in the html element classname. Then in the css, you can write ".ie7 .my-div {float:none;}" Sure, we're not supposed to rely on javascript. But we usually do. And this is just for minor tweaks anyway. The site will still *work* with js turned off, you'd just lose that tiny css tweak you made that relies on it.


  1. If you avoid CSS hacks long enough, some doltish interviewer might think your skills are lacking because you forgot them. "peekaboo bug? What is that? Never heard of it."

  2. "Avoid CSS Hacks" might more properly have been titled "Avoid invalid CSS". CSS hacks most often refer to invalid CSS used for the purpose of targeting browsers. I am simply providing a lightweight alternative that allows simple browser-targeting in css -- with valid syntax.

  3. The concept of the post is simply to provide an easier way to deal with browser inconsistencies and bugs, such as the peekaboo bug, without invalid css. This article did not cover constructing markup and css in a way so as to avoid such browser inconsistencies -- which I feel is impractical anyway.