Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a pesky little space between <img> and other elements? [duplicate]

If a <div> or any other element follows an <img>, then a ~3px whitespace appears in between them — even if margins are zero'd.

<img src="example-fractal-art.png">
<div>What is with that gap?<div>

Here's what it looks like with some CSS.

enter image description here

Now it's pretty easy to throw in display: block into the CSS and solve the problem. But why is it there? There are no computed margins, padding, borders, or anything like that.

What are the browsers doing? Someone even called it "magic".

P.S. Alternatively, in some cases, it is possible to solve this by removing whitespace in the HTML code. (But that doesn't work in this case, why?)

like image 642
Baumr Avatar asked Oct 28 '12 17:10

Baumr


2 Answers

The img is a "replaced element" in HTML, and as such, is it treated as a character. Now in the absence of any styles, the image is aligned with the baseline of the other characters on the line.

So in other words, there is room for the descender underneath the image.

enter image description here

Changing it to a block removes this feature, as you noticed.

like image 111
Mr Lister Avatar answered Nov 10 '22 14:11

Mr Lister


Images by default are aligned with the base line of the text. So if you would put text next to the image, the image would align with the base of an x, but there is a little space (3px apparently) between that base line and the bottom of the line of text.

There you have it:

http://jsfiddle.net/xDCEX/

And you can solve it using vertical-align: bottom if you dont want to make the image a block. That way, the image is still part of the text, but instead of the baseline, it is now aligned to the bottom of the bounding box of the text.

http://jsfiddle.net/xDCEX/1/

Of course, changing it to a display: block also works, but it has other side effect. If everything is working now, changing vertical-align is the easy way.

like image 5
GolezTrol Avatar answered Nov 10 '22 12:11

GolezTrol