Conditional Comments + IE-only Stylesheets
Over at the day job, I ran into a situation where I couldn’t use conditional comments to insert my IE-only stylesheets into the Document. In fact, I didn’t have access to the <head> of the Document at all.
Without any access to the <head> at all, how can we add a stylesheet to the Document? Well, we can do it improperly, by using JavaScript’s document.createStylesheet method to cram our CSS into the body of the Document. Is this where it should go? No. Does it work: yes.
What about making that IE-only? Conditional compilation. By placing the document.createStylesheet call inside some conditionally compiled JavaScript, we’ve achieved the same effect as our conditional comment would. But, what about targeting a specific browser?
With conditional compilation, we have access to the @_jscript_version property of the browser. IE7 uses Jscript version 5.7 and IE6 uses 5.6. Knowing that, we can create an IE6-and-lower-only stylesheet with a one-line test:
@if (@_jscript_version < = 5.6) document.createStylesheet('/path/to/ie6andlower.css');. Voila! A working structure.
Put it all together, and we have a solution that looks something like this:
/*@cc_on
document.createStyleSheet("/css/all_ie_fixes.css");
/*@if (@_jscript_version < = 5.6)
document.createStyleSheet("/css/ie_6_and_below.css");
/*@end
@*/
Is it pretty? Nope, but it works.
Tags: crossbrowser, conditionalcompilation, ie6, ie7, stylesheets, conditionalcomments
January 14th, 2008 at 12:46 am
Just thought… if/when the new jscript version gets pushed to ie6 users, the above code will probably need to be adjusted.
March 13th, 2008 at 6:22 pm
Sounds logical and solid!…But how do I fit this little piece of code in my HTML or PHP page?
I am no Javascript guru and need some more explaining. So could someone please enlighten me a bit more?
March 13th, 2008 at 6:39 pm
Hey Erick,
Here’s a couple of links to take a look at. It’s basically as simple as adding a comment to your webpage.
http://www.quirksmode.org/css/condcom.html
http://blog.amodernfable.com/2006/11/09/css-hacks-you-know-them-you-love-them/
http://blog.amodernfable.com/2007/01/05/ie7-conditional-comment/