【发布时间】:2011-01-11 16:51:00
【问题描述】:
当具有边距的元素包含在另一个元素中时,父元素不会始终环绕/包含该边距。
很多事情都会导致parent包含child的margin:
border: solid;position: absolute;display: inline-block;overflow: auto;
(这只是一个小测试,毫无疑问还有更多。)
我认为这与折叠边距有关,但是:
- W3C 规范页面没有对此类行为的描述。
- 此处没有重叠边距。
- 所有浏览器在这个问题上的行为似乎都是一致的。
- 行为受与边距无关的触发器影响。
默认为overflow: auto 的元素应该包含与溢出设置为自动的元素不同的材料的逻辑是什么?
为什么除了常规 div 的默认行为之外的所有内容都假定边距由父级包含 - 为什么常规默认值不包括边距?
编辑:最后的答案是 W3C 确实指定了这种行为,但是:
- 规范没有任何意义。
-
The specs mix, without any word of explanation:
- 'free margins'(会触及父级顶部或底部的边距不包含在父级中)和
- '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>
【问题讨论】:
-
我不明白你在问什么。您是在问为什么 h1 元素会显示在容器元素中吗?请更清楚您的问题。