Properly Hacking Max-Width for IE6

June 2nd, 2007 @

I’ve been trying to clean up the design of Llynix.com and get it looking relatively the same across the major browsers. One thorn in my side was the fact IE6 doesn’t support the max-width CSS property. It may not seem like a problem to you, but if you are lucky enough to view websites on a widescreen monitor the text has a tendency to run on a bit if max-width isn’t set. Imagine reading this entire paragraph in one line of text. It just doesn’t seem right.

So I apply a max-width which keeps things from running too far off the screen. This works for the major decent browsers, but our old friend IE6 doesn’t understand it. So what’s a web designer to do?

Enter the hack. Luckily IE does have a little piece of javascript that can help us out in faking our max-width. Svendtofte.com has the details of the wonderful snippet below.

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This little ‘expression’ does the same job as max-width:800px; But how do we properly introduce it into our CSS? In the old days we’d rely on faulty CSS error control to splice in various pieces of code for different browsers. Today though we wash our hands of all that, and hopefully ignore such horriable code. There is an easier way.

Enter conditional comments.

Conditional comments only work on Internet Explorer browsers. Other browsers will just treat them as an ordinary comment and continue on. But when IE detects them it will include them if necessary. Zoffix Znet has an excellent article on conditional comments. In addition you might want to check out what Microsoft has to say about them.

Here is my max-width fix inside a IE6 only conditional comment.

    <!--[if IE 6]>
    <style type="text/css">
      #header {width:expression(document.body.clientWidth > 1000? "1000px": "auto" );}
      #mainbody {width:expression(document.body.clientWidth > 800? "800px": "auto" );}
    </style>
  <![endif]-->

Now the webpage looks much better viewed in widescreen in IE6.

Leave a Reply