首先让我说,我不需要帮助解决这个问题 - 我自己可以轻松解决我的具体问题。但我确实需要帮助来理解它发生的原因 - 并可能确定它实际上是一个错误,以便我可以报告它。
问题在于,具有 overflow:hidden
的父容器包含具有负值 margin-bottom
的子容器,后者又包含一个或多个 float
ed 元素后跟一个 clear
(即它的高度取决于 float 的 child )...似乎完全忽略负底边距。
我不希望子 div 的内容对负底边距起到任何作用......无论那个 child 里面是什么,我都希望负边距得到尊重,内容被“切断” "由父级的溢出:隐藏
。
TL;DR: There is a more minimalistic example below...
此示例显示了 FF 和 IE 中的问题 - 但完全符合我在 chrome 中的预期:
* {
box-sizing: border-box;
}
body {
background: tomato;
}
.parent {
overflow: hidden;
background: goldenrod;
width: 25%;
margin: 0 12.5%;
float: left;
}
.parent.overflow_visible {
overflow: visible;
}
.child {
margin-top: -10px;
margin-bottom: -10px; /* THIS ONE has no effect in FF and IE */
}
.float {
height: 100px;
float: left;
border-top: 15px solid green;
border-bottom: 15px solid green;
width: 100%;
}
.clear {
clear: both;
}
.clear_below {
clear: both;
background: yellow;
height: 10px;
}
<div class="parent overflow_visible">
<div class="child">
<div class="float"></div>
<div class="clear"></div>
</div>
</div>
<div class="parent">
<div class="child">
<div class="float"></div>
<div class="clear"></div>
</div>
</div>
<div class="clear_below"></div>
右边的框应该在顶部和底部都有 5px 的边框,框下面的黄色条应该与左边框的“粗”底边框重叠,并且在左边框的“细”底边框的正下方对。
请注意,大部分内容只是为了清楚地形象化 - 问题本身可以用一个不那么冗长的示例重现:
<div style="overflow: hidden">
<div style="margin-bottom: -10px">
<div style="float: left">float</div>
<div style="clear: both"></div>
</div>
</div>
如果“孙子”不 float ,则不会发生此问题:
<div style="overflow: hidden">
<div style="margin-bottom: -60px">
<div><img src="http://via.placeholder.com/350x150"></div>
</div>
</div>
谁能为这种行为提供合理的解释?
最佳答案
这似乎是 Chrome 中的一个错误。
让我们从顶层分解您的示例。您的 .parent
容器是 block 格式化上下文根,因为它们是 float
ing(CSS2.x 规范的 section 9.4.1)。它们指定的 height
是 auto
(默认值)。根据section 10.6.7 ,
...if the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges
float 后代(.float
元素)的底边距边缘是它们的底边距边缘,因为它们自己的底边距为零。该规范没有说明 float 后代的中间 block 包装器,因此 .child
元素的高度小于 .float
元素的事实不应影响容器的高度,结果容器的高度应该由 float 元素(包括它们的边框)的高度决定。这是我们在其他浏览器中看到的,这也是我们在 Chrome 中看到的,如果我们从 .clear
元素中删除 clear: both;
属性。
但是,clear
ing block 的存在以某种方式改变了 Chrome 中容器的行为。浏览器似乎“决定” float 元素下方有一些内容,并开始表现得好像高度由该内容决定,“忘记” float 元素的底部边框实际上在容器本身的底部内容边缘下方(位于 .child
的底部边距边缘)。
因此,如果您想剪裁 block 格式化上下文根的 float 后代,最好为这些 float 元素本身设置负边距。
关于html - 在 FF 和 IE 中完全忽略负边距底部。这是一个错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806760/