Div 元素自动大于指定值?
Div element automagically larger than specified?
无论我如何努力使这个 div
40px 高,它 height
一直在变大。
这是示例 HTML:
div {
/* To prove the div does get larger */
display: table;
background-color: red;
/* Not even explicitly setting height to 40px helps: */
height: 40px;
max-height: 40px;
/* Ofc, problem occurs also without these two lines. */
}
<div>
<img src="http://placehold.it/350x40">
</div>
<img src="http://placehold.it/350x40">
我希望意图很明确:div
应该只和里面的图像一样大。
因为里面的图像是 40px
高,我希望 div
也是 40px
高。
然而,事实并非如此。它不断变大。我已将 background-color
设置为红色以突出显示问题:
是的,以上正是 Firefox 向我显示的内容。我也尝试过 IE 11,结果相同。
我试着查看 Firefox 检查器。似乎出于某种原因,Firefox 将 div
的高度设置为 44.5px
。
为什么会出现这种情况?如何阻止这种行为?
因为img
是内联元素,所以创建space,你必须设置img
显示为块级,你不需要在div
div {
display: table;
background: red
}
img {
display: block
}
<div>
<img src="http://placehold.it/350x40">
</div>
<img src="http://placehold.it/350x40">
更新 来自评论,
The problem is that i kinda need two images in this div, one next to
each other.
改用inline-block
。
div {
display: table;
background: red;
font-size: 0 /* updated from comments */
}
img {
display: inline-block /* updated from comments */
}
<div>
<img src="http://placehold.it/175x40">
<img src="http://placehold.it/175x40">
</div>
<img src="http://placehold.it/350x40">
无论我如何努力使这个 div
40px 高,它 height
一直在变大。
这是示例 HTML:
div {
/* To prove the div does get larger */
display: table;
background-color: red;
/* Not even explicitly setting height to 40px helps: */
height: 40px;
max-height: 40px;
/* Ofc, problem occurs also without these two lines. */
}
<div>
<img src="http://placehold.it/350x40">
</div>
<img src="http://placehold.it/350x40">
我希望意图很明确:div
应该只和里面的图像一样大。
因为里面的图像是 40px
高,我希望 div
也是 40px
高。
然而,事实并非如此。它不断变大。我已将 background-color
设置为红色以突出显示问题:
是的,以上正是 Firefox 向我显示的内容。我也尝试过 IE 11,结果相同。
我试着查看 Firefox 检查器。似乎出于某种原因,Firefox 将 div
的高度设置为 44.5px
。
为什么会出现这种情况?如何阻止这种行为?
因为img
是内联元素,所以创建space,你必须设置img
显示为块级,你不需要在div
div {
display: table;
background: red
}
img {
display: block
}
<div>
<img src="http://placehold.it/350x40">
</div>
<img src="http://placehold.it/350x40">
更新 来自评论,
The problem is that i kinda need two images in this div, one next to each other.
改用inline-block
。
div {
display: table;
background: red;
font-size: 0 /* updated from comments */
}
img {
display: inline-block /* updated from comments */
}
<div>
<img src="http://placehold.it/175x40">
<img src="http://placehold.it/175x40">
</div>
<img src="http://placehold.it/350x40">