Friday, April 20, 2007

Strict mode IE6 bug with CSS "Bottom" style on img tags

While working on part of a new ASP.Net site at work recently, I came across a weird behavior when viewing the page in Internet Explorer 6 where a particular image on the page wasn't staying aligned with the surrounding elements on the page when the browser window was resized. I was able to boil the problem down to a very simple repro case on a basic html page. Here's the source code for the repro page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
  <img src="AnyKey.gif" style="position:absolute;bottom:20px">
</body>
</html>

It turns out that the problem is that for whatever reason, IE6 only recalculates the position of the image relative to the bottom of the browser window when the browser window is resized horizontally -- but not when the browser window is resized vertically! So on IE6, if you resize the browser window to be vertically, the image stays fixed in place, not moving to follow the bottom edge of the window. But when you resize the browser window horizontally, the image immediately pops back into its proper place relative to the bottom edge of the window.

I went ahead and put the repro page up on my website, here -- feel free to take a look if you happen to be using IE6.

Oddly enough, this issue only affects IE6 when in CSS standards-compliance mode; if the page is put into the IE6 quirks mode by deleting the !DOCTYPE tag from the top of the html source, the image does correctly move to follow the bottom edge of the browser window when the window is resized vertically in IE6.

The workaround I found for this issue is simple; just enclose the img tag in a div tag, and put the style attribute on the div tag instead of the img tag:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
  <div style="position:absolute;bottom:20px">
    <img src="AnyKey.gif">
  </div>
</body>
</html>

This odd behavior doesn't happen in the other browsers I tested (IE7 and Firefox 2.0).

I am looking forward to the day when IE6 has been phased out enough that needing to code around its occasional quirky behavior is no longer necessary -- but that day is most likely years away yet!