Fixing CSS with jQuery

One of my coding heros, Lea Verou, came up with a fascinating little script at the beginning of the week: detect CSS selector support using JavaScript. At the time, her script didn’t work in IE. Then I got my hands on it and sorted that little problem. Now that the script works in a wide range of browsers, it opens up a huge range of possibilities for graceful degradation; namely, using JavaScript to fix missing CSS support.

For example, here’s a great way to use jQuery to help bring a few things into line. Take the example of a list that you want to zebra-stripe. You know the way we should be doing that, right? That super-useful :nth-child(even) selector, just like this example. Then your boss sees it and asks what it looks like in IE and you start wondering whether beating him over the head with the stapler will help convince him that it doesn’t matter…

There are two ways I used t handle this (three if you include the stapler): I would either write a catch-all piece of jQuery, or I’d busily go through my markup to do the job manually. Both techniques don’t seem right as they undermine the first piece of CSS.

But now we can check to see if that CSS will work! Using a simple if statement, we can use jQuery to pick up the slack. Now our modern browser will have a much faster and more efficiently-applied style, while browsers that aren’t up to snuff will still display the zebra-striped list. No more cross-browser arguments, no wasted CSS, no bludgeoned boss – everyone’s a winner!

Well… nearly everyone. I think this is a good technique and it’s what I’m currently doing to ensure cross-browser styling, but it’s worth being aware of the limitations. Firstly, you have to duplicate the CSS. I don’t know of any technique to read the rules and apply them to a new stylesheet (though I image it’s possible and I’d love to see it) and secondly, people without JavaScript enabled won’t see the effect. To the second argument I’d say “Yahoo! reckon that over 98% of users who hit their wwebsite have JavaScript enabled, not taking into account those with a browser that understands the original selector” and I’d top it off with “we’re only talking about zebra-striping, those that don’t get the effect still have a perfectly usable list”…

… then I’d look at the stapler…

Leave a Reply

Your email address will not be published. Required fields are marked *