Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra height on wrapper when img is not a block element?

Tags:

html

css

I thought I understood how inline and block elements work, however this has thrown me. I have found a fix for the issue however I have no idea why it works.

For some reason if you have an img inside a div, the div is like 3.5px taller than the image. However if you set the image as a block element this extra height disappears.

Basic HTML:

<div id="wrapper">
        <img src="http://www.basini.com/wp-content/uploads/2013/02/seeing-in-the-dark.jpg" width="300" height="230"  />
</div>

And the CSS:

#wrapper {
    background: orange;
}
#wrapper img {
    /* display: block; this will remove the extra height */
}

I have set up a jsfiddle to demonstrate the effect

Why does this happen and why does making the 'img' a block element fix it? Are there any other solutions?

like image 846
Adam Tomat Avatar asked Mar 12 '13 09:03

Adam Tomat


2 Answers

By default, an image is rendered inline, like a letter.

It sits on the same line that a, b, c and d sit on.

There is space below that line for the descenders you find on letters like j, p and q.

You can adjust the vertical-align of the image to position it elsewhere.

like image 104
zdesam Avatar answered Oct 02 '22 18:10

zdesam


It's due to the line-height of the wrapping div of the img tag.

To fix it, you can set line-height:0 to the div, float the img or display:block the img.

Better explained: How to control line height in <p> styled as inline

like image 23
I.G. Pascual Avatar answered Oct 02 '22 20:10

I.G. Pascual