tags:

views:

842

answers:

6

When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>foo</title></head>
<body>

 <div style="border: solid blue 2px; padding: 0px;">

  <img alt='' style="border: solid red 2px; margin: 0px;"
   src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" />

 </div>

</body>
</html>
+3  A: 

Because the image is inline it sits on the baseline. Try

vertical-align: bottom;

Alternately, in IE sometimes if you have whitespace around an image you get that. So if you remove all the whitespace between the div and img tags, that may resolve it.

John Sheehan
Can you explain your first sentence a little bit more? Why does the image sitting on the baseline cause a gap, and why does changing its vertical-align fix the problem?
raldi
Jim did a great job!
John Sheehan
A: 

Remove the line break before the tag, so that it directly follows the tag with no blanks between it.

I don't know why, but for the Internet Explorer, this works.

koschi
Just to clarify -- this does not work in FF3
rcreswick
+1  A: 
display: block

in the image fixes it as well, but probably breaks it in other ways ;)

tim_yates
Can anyone verify/dispute that this breaks other things?
rcreswick
It means that the image will act as a block, so any elements that should follow it inline will appear on the next available line
tim_yates
A: 

line-height: 0; on the parent DIV fixes this for me. Presumably, this means the default line-height is not 0.

ceejayoz
+6  A: 

Inline elements are vertically aligned to the baseline, not the very bottom of the containing box. This is because text needs a small amount of space underneath for descenders - the tails on letters like lowercase 'p'. So there is an imaginary line a short distance above the bottom, called the baseline, and inline elements are vertically aligned with it by default.

There's two ways of fixing this problem. You can either specify that the image should be vertically aligned to the bottom, or you can set it to be a block element, in which case it is no longer treated as a part of the text.

In addition to this, Internet Explorer has an HTML parsing bug that does not ignore trailing whitespace after a closing element, so removing this whitespace may be necessary if you are having problems with Internet Explorer compatibility.

Jim
That answers absolutely everything I was wondering. Great job.
raldi
A: 

font-size:0; on the parent DIV is another tricky way to fix it.