Thursday, 25 October 2012

X-UA-Compatible Meta Tag Not Working

​You may or may not be aware that you can force IE to render a web page is a specific document mode, which means that an IE9 browser can be forced to render a page as if it was IE8 or IE7.  Why you'd do this is most likely due to the fact that forcing an newer browser to render like an older one (for instance, forcing IE9 to render like IE7) provides a convenient baseline when trying to style a page.

You do this by adding the X-UA-Compatible meta tag to the head block of a page as follows:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This particular line forces IE to render using IE8 mode.  You can read more about it here:

There are a couple of caveats to adding this meta tag.  The first one is that it must be the first meta tag in the head block (there are a coupld of exceptions to this).  The second one is not so obvious, and is the main reason for this article.

If you use conditional comments to render the opening HTML tag of a page (see for details about this) the meta tag just plain doesn't work.  It doesn't matter where you place it in the head block, it just doesn't work.  If you have the same issue, the way around it, as it turns out, is rather simple if a little weird: move it to before the conditional comments like so:

<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->

I've tested this and it appears to continue to work as expected with no downside (apart from ugly HTML).  Hopefully this will help someone out there.

No comments:

Post a Comment