Conditional comments and IE

This is pretty well worn ground, but I managed to do web development for an embarrassingly long time without discovering it: IE5 introduced special syntax that allows regions of an HTML file to be hidden from all but specified IE browsers. The special syntax and affected HTML may be made invisible to non-IE browsers because some of the syntax is similar to that of the comment (“<!-- ... -->“) tag.

The syntax is well covered in this MSDN article, but here is an example. Assume that one wishes to include some IE-specific CSS to make fixed positioning work in IE:

<!--[if gte IE 5.5]>
<![if lt IE 7]>
<STYLE type="text/css">
	/* Fixed position styling for IE 5.5 */
	html {
		background-image:		url("bg.gif");
		background-repeat:		no-repeat;
		background-attachment:		fixed;
	}
	div.header {
		position:	absolute;
		top:		expression(d0 = document.documentElement.scrollTop, (d1 = d0?d0:document.body.scrollTop) + 'px');
		left:		expression(d0 = document.documentElement.scrollLeft, (d1 = d0?d0:document.body.scrollLeft) + 'px');
	}
</STYLE>
<![endif]>
<![endif]-->

To briefly explain: DIVs of class “header” are absolutely positioned, but their top and left values are computed by IE-specific “expressions” that recompute dynamically as the user scrolls the page; the computations have the effect of leaving the DIV in a fixed position in the browser window. The expressions are complicated by the fact that the scrolling information cannot be reliably found in a single part of the DOM, and that the expression won’t reliably auto-update unless an intermediate, “dummy” variable (d1 in this case) is used. A background image is attached to the HTML element to suppress jitter. The whole thing is explained in more detail here.

At any rate, it’s those nifty <!--[if gte IE 5.5]> parts that really caught my attention, and that I think should catch yours. Their effect is to hide this style sheet from all non-IE browsers, IE prior to 5.5, and IE 7 or later. Making things look right in IE is a pretty awful experience, and being able to control what CSS (or HTML) each version of IE can see strikes me as preferable to trying to come up with something that works everywhere, and far preferable to the old bug-based workarounds.

Some nice things about conditional comments:

  • Processed entirely on the client-side; they require no server-side scripting.
  • Processed by the browser’s parsing engine; they require no javascript trickery or user-agent detection.
  • Can mask any HTML (i.e. LINK tags, in addition to STYLE tags).
  • Can be hidden from any non-IE browser.
  • Can be used to control code visibility based on IE major and minor version number.

I was happy to find them.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • Reddit
  • HackerNews
  • del.icio.us
  • Google Bookmarks
  • Slashdot
This entry was posted in Web stuff. Bookmark the permalink.

Comments are closed.