Kesong Xie
Kesong Xie

Reputation: 1396

Why the parent height is not the same is inner image height?

I have been working on css for a while, but I was confused why the parent height is not the same as the inner image height, given the following code.

<div style="width:200px">
    <img style="max-width:100%;" src="http://localhost:8888/example/06f1e47fbdb03e48203ebfba/66932afa697bdbc76a1a291e/thumb_d90ab4a531969620e2c2a160.jpg">
</div>

I was expect that the parent div would expand correspondingly with different image. The fact is that the inner image is 200*200, and the outer div is 200*206, and I have no idea where does the extra 6 pixels comes from. There is are padding for the outer div or margin for the inner image. Could someone explain why this happens?

Upvotes: 5

Views: 1143

Answers (3)

C3roe
C3roe

Reputation: 96306

Could someone explain why this happens?

Because the image is a replaced inline element, and as such it is per default aligned on the baseline of potential text content on the same line.

Making it block as already mentioned in another answer, or specifying vertical-align:bottom for it changes that.

Upvotes: 1

TechWisdom
TechWisdom

Reputation: 4285

Use display: block;

div {
  width:200px
}

img {
  max-width:100%;
  display: block;
}
<div>
    <img src="http://cadizinc.com/wp-content/uploads/2011/11/water_07-610x370.jpg">
</div>

Upvotes: 0

Matthew King
Matthew King

Reputation: 1362

Does this fix the problem for you? If not, what browser and OS are you using?

I've run into this before. The issue is that images, by default, are display: inline-block, which causes them to behave like text (following the text baseline for example). In cases where we do not want this to happen, we can change the display to display: block.

Upvotes: 5

Related Questions