gpt4 book ai didi

html - 为什么这个 CSS margin-top 样式不起作用?

转载 作者:行者123 更新时间:2023-11-28 05:17:19 26 4
gpt4 key购买 nike

我试图在另一个 div 内的 div 上添加 margin 值。除了最高值外,一切正常,它似乎被忽略了。但是为什么?

我的预期:
What I expected with margin:50px 50px 50px 50px;

我得到的:
What I get with margin:50px 50px 50px 50px;

代码:

#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

您可以执行以下任一操作来防止边距折叠:

上述选项阻止边距折叠的原因是:

  • 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/39246616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com