Explain Codes LogoExplain Codes Logo

Image inside div has extra space below the image

html
responsive-design
css
layout
Anton ShumikhinbyAnton Shumikhin·Sep 24, 2024
TLDR

Remove the extra space below an image inside a div by setting the image display property to block. This counteracts the default inline behavior that reserves space for text descenders. Use the following CSS rule:

img { display: block; /* Just going from inline to block-star! */ }

Incorporate it in your image element to eliminate unwanted spacing:

<div> <img src="image.jpg" alt="" style="display: block;"> </div>

Like magic - no more extra space beneath your image.

Inline elements and vertical alignment

The inline dilemma

Images, by default, are considered as inline elements and align with the baseline - the imaginary line upon which text rests. This alignment leaves an unwanted space beneath images reserved for text descenders.

If display: block; doesn't suit your style, tweaking the vertical-align property is your next best bet:

img { vertical-align: middle; /* Plays nice and aligns with others */ }

This aligns the middle of the image with the baseline plus half the x-height of the parent, eliminating any surprising gaps.

Dealing with replaced elements

Remember images are replaced elements, their default inline-block behavior dictates how much space they occupy. Different browsers may render these elements slightly differently, consider this factor when designing your layout.

Containing the issue

Tampering with line-height

In some cases, setting the line-height of the image's parent element to 0 can eliminate extra image space.

div { line-height: 0; /* The enemy of extra space */ }

Playing detective with borders

Adding temporary borders to your images and divs can help identify and debug any extra space issues:

div, img { border: 1px solid red; /* Now you see me! */ }

Tangling with additional factors

Responsiveness and aspect ratios

For responsive designs, consider aspect ratio boxes to maintain the correct size and aspect of your images on any device.

Taking explicit measures

Defining explicit width and height on your images can help prevent layout shifting or reflow when images are still loading.

img { width: 300px; height: 200px; }