CSS min-height 添加到 child 元素的底部边距
CSS min-height adds to child element's bottom margin
我遇到了一个非常奇怪的 CSS 问题。我的一些页面在元素之间显示了无法解释的 "space"。检查代码显示此 space 不属于任何元素。
我已经缩小了范围,我想我知道为什么会出现这个问题。但我想知道,在幕后,为什么会这样。
我认为,问题在于 #outer
选择器中的 min-height: 50px
在 #outer
下面添加了 #inner
的下边距,这导致无法解释的 space 上面提到过。如果将其替换为 height: 50px
,则 space 将消失。
这发生在 Chrome 而不是 FireFox。
我的理论是 Chrome 的 CSS 首先布置元素,然后检查是否满足 min-height 要求。如果不是,则它会扩展 div 的高度,同时推动 "unexplained space"。它本质上复制或继承了 child 元素的底部边距。我认为这只会发生在底部边距上。
我已经对这个理论进行了两次测试,添加 padding: 1px;
和添加 overflow: hidden;
它们都会导致 div 的高度包含它的 child 因此摆脱这个问题。虽然,我认为在 overflow: hidden
的情况下,它更多地切断了溢出的内容。
但我不是 CSS 专家,所有这些都只是我的猜测,这就是为什么我想提出这个问题:)
这是代码
#outer {
background-color: blue;
min-height: 100px;
}
#inner {
background-color: red;
height: 50px;
margin-bottom: 50px;
}
#bottom {
background-color: green;
height: 50px;
}
<div id="outer">
<div id="inner">
</div>
</div>
<div id="bottom">
</div>
这是由于 margin collapsing
- 特别是 inner
的 margin-bottom
崩溃 成为 margin-bottom
outer
元素.
解决方案:
给 outer
元素一个 border
以防止边距折叠 - 请参见下面的演示:
#outer {
background-color: blue;
min-height: 100px;
border: 1px solid blue;
}
#inner {
background-color: red;
height: 50px;
margin-bottom: 50px;
}
#bottom {
background-color: green;
height: 50px;
}
<div id="outer">
<div id="inner">
</div>
</div>
<div id="bottom">
</div>
我遇到了一个非常奇怪的 CSS 问题。我的一些页面在元素之间显示了无法解释的 "space"。检查代码显示此 space 不属于任何元素。
我已经缩小了范围,我想我知道为什么会出现这个问题。但我想知道,在幕后,为什么会这样。
我认为,问题在于 #outer
选择器中的 min-height: 50px
在 #outer
下面添加了 #inner
的下边距,这导致无法解释的 space 上面提到过。如果将其替换为 height: 50px
,则 space 将消失。
这发生在 Chrome 而不是 FireFox。
我的理论是 Chrome 的 CSS 首先布置元素,然后检查是否满足 min-height 要求。如果不是,则它会扩展 div 的高度,同时推动 "unexplained space"。它本质上复制或继承了 child 元素的底部边距。我认为这只会发生在底部边距上。
我已经对这个理论进行了两次测试,添加 padding: 1px;
和添加 overflow: hidden;
它们都会导致 div 的高度包含它的 child 因此摆脱这个问题。虽然,我认为在 overflow: hidden
的情况下,它更多地切断了溢出的内容。
但我不是 CSS 专家,所有这些都只是我的猜测,这就是为什么我想提出这个问题:)
这是代码
#outer {
background-color: blue;
min-height: 100px;
}
#inner {
background-color: red;
height: 50px;
margin-bottom: 50px;
}
#bottom {
background-color: green;
height: 50px;
}
<div id="outer">
<div id="inner">
</div>
</div>
<div id="bottom">
</div>
这是由于 margin collapsing
- 特别是 inner
的 margin-bottom
崩溃 成为 margin-bottom
outer
元素.
解决方案:
给 outer
元素一个 border
以防止边距折叠 - 请参见下面的演示:
#outer {
background-color: blue;
min-height: 100px;
border: 1px solid blue;
}
#inner {
background-color: red;
height: 50px;
margin-bottom: 50px;
}
#bottom {
background-color: green;
height: 50px;
}
<div id="outer">
<div id="inner">
</div>
</div>
<div id="bottom">
</div>