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

标签 html margin css

我试图在另一个 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/42736106/

相关文章:

html - 溢出属性 -x :hidden; and -y:visible

javascript - 如何在没有 iframe 的情况下使用 Google 表单?

html - 使我的页面在调整大小时看起来不错...使用宽度 80%

javascript - 使用鼠标滚轮移动图像

HTML 和 CSS 菜单

CSS - 按钮有时无法点击?

html - margin:auto 似乎不起作用,无法弄清楚

html - 如何在我的html输入中放置颜色边框

html - Bootstrap 移动菜单 100%

css - bootstrap-vue 改变 <b-modal> 的位置