当具有边距的元素包含在另一个元素中时,父元素不会始终包装该边距 .
很多事情会导致父母包裹孩子的边缘:
-
border:solid;
-
位置:绝对;
-
display:inline-block;
-
溢出:自动
(这只是来自小型测试,毫无疑问还有更多 . )
我认为这与折叠边距有关,但是:
-
W3C规范页面没有此类行为的描述 .
-
这里没有重叠的边距 .
-
所有浏览器的行为在此问题上似乎都是一致的 .
-
行为受与边距无关的触发器影响
默认溢出的元素的逻辑是什么:auto应该包含与溢出设置为auto的材料不同的材料 .
为什么除了常规div的默认行为之外的所有内容都假定父级包含保证金 - 为什么常规默认值不包括保证金?
编辑:最后的答案是W3C确实指定了这种行为,但那
-
规格没有任何意义 .
-
'free margins'(父母不包含触及其父母顶部或底部的边距)和
-
'collapsed margins'(允许相邻边距重叠) .
演示:
<!doctype html>
<html>
<head>
<title>Margins overextending themselves</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css">
body{
margin:0;
}
div.b{
background-color:green;
}
div.ib{
display:inline-block;
background-color:red;
}
div.pa{
background-color:yellow;
position:absolute;
bottom:0; right:0;
}
div.oa{
background-color:magenta;
overflow:auto;
}
div.brdr{
background-color:pink;
border:solid;
}
h1{margin:100px; width:250px; border:solid;}
</style>
</head>
<body>
<div class="b">
<h1>Is the margin contained?</h1>
</div>
<div class="ib">
<h1>Is the margin contained?</h1>
</div>
<div class="pa">
<h1>Is the margin contained?</h1>
</div>
<div class="oa">
<h1>Is the margin contained?</h1>
</div>
<div class="brdr">
<h1>Is the margin contained?</h1>
</div>
</body>
</html>`
1 回答
这就是CSS的工作原理according to W3C:
更具体到你的顶级div的情况:
我能做的最好的事情就是指向"Collapsing Margins" on sitepoint(汤米奥尔森和保罗奥布莱恩) . 他们做了一个详细的解释,其中的示例显示了您在问题示例代码中演示的行为 .