Twitter Email
silvercircle No addendum
A Jekyll test site with no particular purpose.

Strange unwanted padding around images and how to fix

Author: AlexVie
Title: Strange unwanted padding around images and how to fix
Language: en-US
Created: 12:19 on Monday, 04. September 2017
Modified: 12:20 on Monday, 04. September 2017

Sometimes, images enclosed by divs or other block level elements show apparently strange and unwanted 2-3 pixels of padding on the bottom edge even though the containing element has no padding set at all.

Tags: first
Page layout: topics_dyn
Last modified:
301 Words
12:19 | by AlexVie
Reading time: approx. 1 minute(s).

The problem:

… 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.