There are many frustrations that I have had in my short dev game so far, and one of them crossed my eyes very recently again while I was working on a small project of mine.
It is this strange gap when using the HTML
<img> tag that made me go wild already quite a few times:
But not this time!
The reasoning and the solution to this problem is actually really simple and has to do with the text of the box.
Wait, what? There is no text in the picture!
As it turns out,
img elements are by default inline elements. This means they basically flow the same as text. As such the bottom edge of the image is aligned with the baseline of the font that is specified with the
Mystery solved! Here's how you can fix this issue:
On your image, set
Set your image to
display: block (Then you also have to specify a width for your image or otherwise everything will fall into the next line)
Edit: You can also fix this issue while using more modern techniques. So, setting
grid (also needs a width to be set), or their inline counterparts
inline-grid will also work while giving more flexibility as
display: block (and also work when applied to the image container).
Don't use images all together (makes your site faster)
Maybe this is exactly what you want! Aligning an image or small icon within your text flow on the baseline couldn't be easier!
Set the image container (parent) to
line-height: 0 (does not work when the container is an
inline element) or
font-size: 0 (always works)
On the image, set
In the end the "mysterious image gap" isn't that mysterious at all, and still, it is quite interesting where such simple frustrations can lead. After all, I have a more thorough understanding how inline elements behave now.
Here are some more resources if this wasn't enough:
- or just search for "html img gap" or "img tag gap" in your favorite search engine and let the thousand Stack Overflow issues sink in your mind
Thank you for reading :)
If you want to find out more about the details of HTML layout
You may also want to check out the HTML reference on the Mozilla Developer Network.
Some further reading: