9

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Adam Tomat
  • 11,206
  • 6
  • 39
  • 47

3 Answers3

10

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.

zdesam
  • 2,936
  • 3
  • 25
  • 32
  • You can also set the line-height of the div containing the image to 0 to remove below space, but this is not good if the div contains multiple line text as well – zdesam Mar 12 '13 at 09:07
3

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

Community
  • 1
  • 1
I.G. Pascual
  • 5,818
  • 5
  • 42
  • 58
  • Thanks, don't really want to set the line-height to 0 because I actually have text in that wrapper too. And I guess floating the image works because a floated element also becomes a block element. Good to know though +1 – Adam Tomat Mar 12 '13 at 09:14
0

have you tried to reset all styles? before applying new styles?

Jordy van Eijk
  • 2,718
  • 2
  • 19
  • 37