Checking for CSS rule value support in IE

I’ve learned to prefer * and _ hacks over conditional comments to target IE for two reasons—users won’t need to make yet another HTTP request, and perhaps more importantly, code in one file is much easier to maintain than the same code in two or more files (DRY).

Recently, it occurred to me that this can also be used as a more granular way to target IE instead of browser sniffing. Similar to testing for the existence of a JS property/method before using it, I can basically check if a certain CSS rule value is supported. Note that this is different from checking CSS rules like -moz-border-radius, which can be directly accomplished in JS.

For example, IE6 does not support position: fixed, but other property values like absolute and relative are fine. So if I want to run some JS code only in IE6 to emulate fixed positioning (lots of existing workarounds use CSS expressions which I’d rather avoid), I can do the following:

#foo {
    position: fixed;
    _position: absolute;
}
var isPositionFixed = (fooEl.style.position == 'fixed');
if (!isPositionFixed) {
    // Special sauce for IE6
}

Here, isPositionFixed will always evaluate to false in IE6 since all other browser will ignore it, which I think is much more reliable and cleaner than user agent sniffing. Admittedly, this does blur the line between presentation and behavior, but it is not a terrible compromise that I’m willing to take.

Till shitty browsers drop off the face of the planet, here’s yet another hack to live with.

Leave a Reply