当具有边距的元素包含在另一个元素中时,父元素不会始终包裹/包含该边距。
许多事情会导致父母包含孩子的边距:
border: solid;
position: absolute;
display: inline-block;
overflow: auto;
(这只是一个小小的测试,毫无疑问还有更多。)
我认为这与折叠边距有关,但是:
- W3C 规范页面没有对这种行为的描述。
- 这里没有重叠的边距。
- 在这个问题上,所有浏览器的行为似乎都是一致的。
- 该行为受到与边距无关的触发器的影响。
默认的元素overflow: auto
应该包含与溢出设置为自动的元素不同的材料的逻辑是什么?
为什么除了常规 div 的默认行为之外的所有内容都假定边距由父级包含 - 为什么常规默认值不包括边距?
编辑:最后的答案是 W3C 确实指定了这种行为,但是:
- 这些规格实际上没有任何意义。
- 规格混合,没有任何解释:
- '自由边距'(会触及其父级顶部或底部的边距不包含在父级中)和
- 'collapsed margins'(允许相邻的边距重叠)。
演示:
body {
margin: 0;
}
div.block {
background-color: skyblue;
}
div.inline-block {
display: inline-block;
background-color: lawngreen;
}
div.position-absolute {
background-color: rgba(255,255,0,.7);
position: absolute;
bottom: 0;
right: 0;
}
div.overflow-auto {
background-color: hotpink;
overflow: auto;
}
div.border {
background-color: aquamarine;
border: solid;
}
h2 {
margin: 80px;
width: 250px;
border: solid;
}
<div class="block">
<h2>Is the margin contained (block)?</h2>
</div>
<div class="inline-block">
<h2>Is the margin contained (inline-block)?</h2>
</div>
<div class="position-absolute">
<h2>Is the margin contained (position-absolute)?</h2>
</div>
<div class="overflow-auto">
<h2>Is the margin contained (overflow-auto)?</h2>
</div>
<div class="border">
<h2>Is the margin contained (border)?</h2>
</div>