Strange unwanted padding around images and how to fix
… is best demonstrated by example. The container, a
divelement with a red
border and a padding of 4 pixel, shall contain an image. We want equal padding on all 4 sides and a
one pixel wide border around the container.
As you can clearly see, the padding below the image is larger than on the other three sides even though the padding for the surrounding container is set to 4px on all sides and the margin for the
img element is set to zero.
At first, it looks like a browser issue or some rogue CSS margin or padding attribute affecting the placement, but it’s not. You can verify that it will look the same in all modern browsers and the rogue CSS theory can be counteracted by explicitly setting all margins and paddings to zero, using a style= attribute (which is exactly what I did in the example above).
This happens, because
img elements are inline elements by default. Such elements are treated
like text and therefore the browser will align them to the baseline of the surrounding text grid.
Inline elements will receive automatic vertical padding, that depends on their alignment and
placement. So what the browser does is correct and required by specifications.
The fix is fairly easy. Just make the image a block element.
<img src="/assets/gfx/thumb_vim.png" alt="image" style="display:block;">
Now, the unwanted additional padding on the bottom edge is gone. The image behaves like a block element and will perfectly fit in the surrounding box model.