File Under: Web Basics

Tiny JavaScript Solves Cross-Browser Stylesheet Woes

CSSWriting cross-browser CSS is a complicated and difficult process. While modern browsers behave in similar, standards-compliant ways, older browsers don’t. That means, at some point, you’re probably going have to resort to some hacks. We’ve outlines some possible solutions — like using a CSS “reset” file, but there are plenty of cases where that isn’t enough.

Most CSS hacks involve tiny code tweaks to target certain browsers, but designer Jeff Croft recently point out another possibility — a very easy-to-use and elegant JavaScript solution named CSS Browser Select.

CSS Browser Select is the brainchild of Rafael Lima, who was inspired by an idea on the 37 Signals blog. The result is CSS Browser Select which works by adding a browser-specific class name to your HTML elements. You then have ability to write specific CSS code for each operating system and each browser. And all that comes with only a 1k overhead.

Using CSS Browser Select works like this:


.mac.opera #my-header { margin: 1em; }

This rule would tell the Mac OS version of Opera to set the margin of my-header to 1 em. All other browsers would ignore the rule.

It’s a very slick and easy solution to the complicated problem of targeting specific browsers. Of course, as a number of commenters on Croft’s site point out, it might be a tad overkill for the general problem — IE 6. Since probably 90 percent of all CSS hacks are designed to solve IE 6′s issues, conditional comments are probably a better solution (no JavaScript required).

Still, for those cases where you need to do something rather unusual across a number of browsers, CSS Browser Select is one of the best solutions we’ve seen.

[Photo by Adactio, Flickr]

See Also: