Mysterious space beneath images

Mysterious space beneath images

Images are everywhere on the web. In today’s world, no website is complete without using images. When using an img tag in HTML to render images, have you ever noticed a mysterious space beneath the image?

An code example of image and space beneath the image

Take the example above, we have an image with a width of 500px and height of 350px wrapped inside the div with a border. Notice that the height of the div in the box model is 354px which is a little bit bigger than the height of the image. Take a closer look.

An images on the web with space beneath

Where is this space coming from? and how do we solve this?

Here is a deal. img is an inline element and the browser treats it as typography and adds this space so that it doesn’t place those elements too tight. This makes sense with texts though.

There are two ways we can solve this problem.

  1. Change the display property of images to display: block

Solved code example with display block property

  1. Setting the line height of the parent div to 0

line-height CSS property is used to set the distance between two lines of text and we can leverage this to our advantage.

Solved code example with css line height property

You can find the codepen here: https://codepen.io/Junaid-Shaikh-the-lessful/pen/BabxZoZ

I hope that was useful for you. Thank you for taking the time to read this. You can find me on Twitter and Linkedin

Cover pic by Natalia Trofimova on Unsplash