Wrong height of div with img tag inside

user1403825 picture user1403825 · May 18, 2012 · Viewed 22.3k times · Source

I have a div with an image tag inside, and the div height appears to be a little larger than the image.

I could fix this problem by setting a specific height for the div (the same as the image), but I'm working with a responsive layout, and I don't want to set a specific height for the div, so that when the browser window scales (for example in mobile devices) the div will scale and maintain the ratio.

I need that the div height to be exactly as the image height.

This is the scenario:

<div class='box'><img src='image.jpg'></div>

Css is:

img { height: auto; max-width: 100%; width: auto; }

Does anybody know how to fix this problem?

Screenshot

Answer

Brodie picture Brodie · May 18, 2012

The problem is that the image's natural styling gives it a little bit of margin on the bottom making it ugly to say the least. An easy fix is to just display: block, float: left on the image and the space should go away.

either that or you can play around w/ the border-collapsing on the image if you really don't want to float it. However, that's a solution that would probably cause more problems in the end.

so it's going to end up being something like

.box img {
  display: block; /*inline block would be fine too*/
  float: left;
}

hope that helps.