Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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>
like image 612
raldi Avatar asked Sep 24 '08 19:09

raldi


People also ask

How do I get rid of the gap under my image?

In order to get rid of additional white space, there are 3 properties that can be used: Using the display property. Using vertical-align property. Using line-height property.

Is the space between the border of the box and the content?

The Architecture: The content is surrounded by the border, the space between the content and the border is called the padding, while the space between the border and the other elements in the document is called the margin.


3 Answers

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.

like image 129
Jim Avatar answered Oct 21 '22 19:10

Jim


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.

like image 25
John Sheehan Avatar answered Oct 21 '22 19:10

John Sheehan


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

like image 4
ceejayoz Avatar answered Oct 21 '22 21:10

ceejayoz