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/48982351/

相关文章:

html - 内表内容与外表不对齐

javascript - 如何将视差对齐到 div 的中间?

css - Modernizr 测试是否包含以浏览器为前缀的功能?

html - 如何防止 flex 容器中的选择框缩小?

php - 设置输入值而不是让用户输入

javascript - 如何在LEVEL 3的表单提交中获取LEVEL 4's select element'的值?

javascript - 如何使滚动网站移动友好?

linux - 使用 PDFTK 或类似工具合并时向 PDF 文件添加边距

html - CSS 单元格边距

CSS3 定位多个类中的多个元素