Mysterious padding/margin appears after image in strict mode
I created a new document both with xhtml 1.0 and html 4.01 STRICT just to isolate this. All I have in its body is:
<div style="border: blue 3px solid;">
<img src="testimage.jpg" width="800" height="400">
</div>
The result is normal except there's a 5px space below the image that goes away if I change the doctype to transitional. It also goes away if I set display: block to the image.
You can see the result yourself here (I know the white space on the right is normal since its a block element): http://i52.tinypic.com/2prd1jd.jpg
I tried setting margin/padding to 0, even this:
*
{
margin: 0; padding: 开发者_如何学JAVA0;
}
but it's still the same.
Can anyone please explain this behavior?
It has to do with vertical alignment of the image. Try this:
img{
vertical-align: top;
}
and the space will go away.
To clarify, if you put some text next to the image you will see the issue. The image is aligning with the base of the text but letters like y and g will go below that line. The extra space is for those overhanging letters.
This is because, as mentioned by @Pawel, "by default, an image is rendered inline". Since it is "inline" some spaces below will be given for characters like 'g,j,q,y' etc.
- The image is from: https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps .
So another solution is just set the image as block:
img {
display:block;
}
An example is here: https://gist.github.com/MrCoder/450783bc33d6b412075d
精彩评论