解决包含img的div底部多出了3px

先说现象

1
2
3
4
5
6
7
8
9
<!DOCTYPE HTML>
<body>
<div class="top" style="background-color:#f00;">
<img src="http://p1.bpimg.com/567571/578c5c39b2f1e41f.jpg" alt="" />
</div>
<div class="body">
...代表
</div>
</body>

上面的示例代码,会让top出现3px的margin-bottom ,就是这么吊。

其中<!DOCTYPE HTML>是必须滴。

解决方法

A.给img设置display: block

1
2
3
img {
display: block;
}

B.给img设置vertical-align

1
2
3
img {
vertical-align: top/middle/...;
}

C.给img他爸爸设置font-size: 0

1
2
3
.top {
font-size: 0;
}

D. …

上面测试都通过,想知道为什么?。

为什么

据传说,这是浏览器在给y.g这种腿长的字母预留的空间,大概…就是3px,可能是因为img长的太像它们了,所以也给了3px。

This problem is caused by the image behaving like a character of text (and so leaving a space below it where the hanging part of a “y” or “g” would go), and is solved by using the vertical-align CSS property to indicate that no such space is needed. Almost any value of vertical-align will do; I’m fond of middle, personally.

The problem is caused by vertical-align: baseline, which is the default for most elements and indicates that that space should be reserved. Some of the other legal values for vertical-align also reserve this space, but top, text-top, middle, bottom and text-bottom do not. sub also doesn’t appear to, but I’m leery of trusting that one. – Brilliand Jun 1 ‘12 at 4:20

参考: