Images gain a mysterious empty space underneath, even if padding:0;margin:0
are applied.
Demonstration
The red border should hug the image, but there is space on the bottom side.
What causes this, and how can I remove this space?
Display Property: The most commonly used solution is used to change the display property of the <img> tag inside the <div> container from default 'inline' value to 'block' using display : block property.
It happens because image is an inline-level element so browser adds some whitespace under the baseline to adjust other inline elements.
In this configuration, the bottom of the image is aligned on the baseline as you can see in this example: This is why the default behaviour of the <img> tag creates a gap at the bottom of it's container and why changing the vertical-align property or the display property removes it as in the following demo:
If you try to put an image inside a <div> element that has borders, you will see an extra white space (around 3px) at the bottom of image. It happens because image is an inline-level element so browser adds some whitespace under the baseline to adjust other inline elements.
<img> has no baseline, so when images are used in an inline formatting context with vertical-align: baseline, the bottom of the image will be placed on the text baseline. As browsers by default compute the vertical-align property to baseline, this is the default behaviour.
Images (and inline-block elements in general) are treated like a character.
As such, they obey the rule of the baseline.
In normal text, the baseline is the line across the bottom of most letters, such as in this sentence.
But some letters, such as p
, q
, j
and so on, have tails that drop below the baseline. In order to prevent these tails from colliding with letters on the next line, space is reserved between the baseline and the bottom line.
This diagram illustrates the different lines used by text:
(Image from WHATWG)
So, the image is aligned to the baseline, even if there is no text. Fortunately, the fix is very simple:
img {vertical-align:bottom}
This will align the image to the bottom of the line, also removing the mystery space.
Just be careful, if your image is small (smaller than the line height), you may start seeing mystery space appearing above the image instead. To fix this, add line-height:1px
to the container element.
Hopefully this helps the many people I've seen ask about this and similar problems!
Changing img
to a block level element
img { display: block; }
will also remove the space below the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With