Steve Jobs Steve Jobs - 9 months ago 20
CSS Question

When I put a div around an image, why is there spacing at the bottom?

Take for example this fiddle: https://jsfiddle.net/ou33muc2/

<div class = "overallDiv">
<div id="example"><img src = "http://writingexercises.co.uk/images2/randomimage/slimy.jpg" style="width:100vw; opacity: 0.5;"/></div></div>


I fail to understand why there is no gap between the div surrounding the image and the image on the top, left and right, but there is a gap on the bottom as shown by the red border.

Moreover, how can I remove this, so that the div fits snugly around the whole image?

Edit: I know it might seem a bit pointless having a div around a div around an image, but this is a scaled down problem where the question still applies, so please ignore the practicalities of it.

Answer Source

Because the image is vertically aligned at the baseline - where text usually would be placed. And there's space below the baseline, for letters with "descenders" like j, g, p etc.

To avoid that, just add line-height: 0; to the container:

https://jsfiddle.net/5czathrh/1/ (edit: updated)