Image inside div has extra space below the image
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:
Incorporate it in your image element to eliminate unwanted spacing:
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.
Navigating through vertical alignment
If display: block;
doesn't suit your style, tweaking the vertical-align
property is your next best bet:
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.
Playing detective with borders
Adding temporary borders to your images and divs can help identify and debug any extra space issues:
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.
Was this article helpful?