25

Why does the parent div of the image have a few extra pixels at the bottom. How can I remove the pixels without hard code the parent div height.

http://jsfiddle.net/6x8Dm/

HTML

<div class="wrapper">
    <div class="column">
        <img src="http://www.lorempixel.com/200/200/" />
    </div>    
</div>  

CSS

.wrapper {
    width:200px;
    margin:0 auto;
}
.column {
    width:100%;
    background:#cc0000;
}

img {
    width:100%;
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Adrian Florescu
  • 4,454
  • 8
  • 50
  • 74

2 Answers2

54

That space actually is a result of descender elements in fonts. You can get rid of it in a number of ways:

j08691
  • 204,283
  • 31
  • 260
  • 272
  • @JoshC Really interesting answer. I guess this margin is there because of the alt text in case the image is missing. Do you have any idea about the reason behind this extra pixels? The reason? – Adrian Florescu Oct 06 '13 at 18:47
  • 3
    @AdrianFlorescu - no, the gap (not a margin) is there because by default images are like inline elements and the space is reserved for descender elements (e.g. g, y, j). – j08691 Oct 06 '13 at 18:52
  • 2
    Thank you so much ! These 4 pixels in extra height were breaking my code. – vinni Nov 02 '16 at 23:13
  • I was in a similar boat but with many intervening divs between the image and where the extra space showed up. Bootstrap puts `display: block` on .img-responsive already, but 4 levels or so up, there was a `display: inline-flex` div under a `display: block` div, and sure enough that's where the gap was. Adding `vertical-align: top` to my inlined div did the trick! – John Neuhaus Nov 02 '20 at 18:29
  • 1
    FYI for the confused, descender elements are letters with tails, not _descendant_ HTML elements (hence why 'g' 'y' 'j' are examples.) See [this answer on another question](https://stackoverflow.com/a/17905828/3499424) (which I think is technically a duplicate Q) – John Neuhaus Nov 02 '20 at 18:33
  • I can't thank you enough. Very interesting answer that I didn't expect. – GeorgeCiesinski Aug 10 '22 at 00:14
7

One way is by setting display:block on the img, causing it to fill the parent.

jsFiddle here - it works.

img {
    width:100%;
    display:block;
}

Alternatively, if you don't like that approach, you can also change the vertical alignment, as the default is baseline.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Hm... cool! That is correct! Do you have any idea why is that margin there? – Adrian Florescu Oct 06 '13 at 18:35
  • 1
    I imagine the guys when they created the image tag. They where like... "We should add a few extra pixels under this image if it's wrapped into a div and no display property or float is added - it will be creepy :)) muahaha" – Adrian Florescu Oct 06 '13 at 18:40