raldi
raldi

Reputation: 22160

Why is there a gap between my image and its containing box?

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">

<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>

Upvotes: 12

Views: 14079

Answers (6)

Anne
Anne

Reputation:

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

Upvotes: 1

Jim
Jim

Reputation: 73936

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.

Upvotes: 22

ceejayoz
ceejayoz

Reputation: 180024

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

Upvotes: 4

tim_yates
tim_yates

Reputation: 171084

display: block

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

Upvotes: 3

Thomas Koschel
Thomas Koschel

Reputation: 3361

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.

Upvotes: 1

John Sheehan
John Sheehan

Reputation: 78124

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.

Upvotes: 6

Related Questions