我试图在另一个 div
内的 div
上添加 margin
值。除了最高值外,一切正常,它似乎被忽略了。但是为什么?
代码:
#outer {
width: 500px;
height: 200px;
background: #FFCCCC;
margin: 50px auto 0 auto;
display: block;
}
#inner {
background: #FFCC33;
margin: 50px 50px 50px 50px;
padding: 10px;
display: block;
}
<div id="outer">
<div id="inner">
Hello world!
</div>
</div>
W3Schools没有解释为什么 margin
会这样。
最佳答案
您实际上看到了 #inner
元素的上边距 collapse到 #outer
元素的顶部边缘,只保留 #outer
边距不变(尽管未在您的图像中显示)。两个盒子的顶部边缘彼此齐平,因为它们的边距相等。
以下是 W3C 规范中的相关要点:
8.3.1 Collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
Adjoining vertical margins collapse [...]
Two margins are adjoining if and only if:
- both belong to in-flow block-level boxes that participate in the same block formatting context
- no line boxes, no clearance, no padding and no border separate them
- both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
- top margin of a box and top margin of its first in-flow child
您可以执行以下任一操作来防止边距折叠:
- Float either of your
div
elements- Make either of your
div
elements inline blocks- Set
overflow
of#outer
toauto
(or any value other thanvisible
)
上述选项阻止边距折叠的原因是:
- Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
- Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
- Margins of inline-block boxes do not collapse (not even with their in-flow children).
左右边距的行为符合您的预期,因为:
Horizontal margins never collapse.
关于html - 为什么这个 CSS margin-top 样式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982351/