Gotta love IE’s little surprises. I’m not sure if this is a known bug, in fact I’m not even sure if this is a bug at all, but I thought I’d write it up for future reference.
One of the challenges of laying out pages in HTML is that there’s no native way to associate a caption with an image so that the caption’s width is constrained to the width of the image.
In order to accomplish this, we wrap both the image and the caption in a
div with the width set to be exactly the width of the image. Because both the image and the caption are inline elements, this should force the caption below the image and cause the text to wrap appropriately for the size of the image.
Here’s some test code to demonstrate what I mean. Note: I’ve added the red border in order to make the
div easier to see.
<div style="width:100px;border:1px solid red;"> <img src="caption-bug-test-image.gif" width="100" height="100" alt="caption bug test image" /><em>This is the caption for this test image</em> </div>
Now in Firefox, the code above looks just like we want it to:
However, Internet Explorer interprets the HTML above in a vastly different way:
Because there’s no whitespace between the
img tag and the caption (surrounded by
em tags), IE chooses to break the line after the first word in the caption rather than before. The best (read: most annoying) part is that if I modify the source above to include a newline in between the image and the caption like so:
<div style="width:100px;border:1px solid red;"> <img src="caption-bug-test-image.gif" width="100" height="100" alt="caption bug test image" /> <em>This is the caption for this test image</em> </div>
…then IE behaves as expected (or at least closer to expected):
<br /> tag between the image and the caption also works in both IE and FF without adding an extra line between the image and the caption, but that’s an annoying thing to have to enforce. Might make sense though considering that an image is an inline element.
Of course in this context we’re essentially treating the image like a block level element. So another solution would be to create a class for our image container
divs that sets a CSS
display:block; rule for any image inside the
div. Except sometimes we include multiple images (side by side) inside the
div. Oh shucks.