html - 为什么水平边距不会像垂直边距一样折叠?

标签 html css dom

我明白为什么会发生边距崩溃;我在各种网站上看到了一些关于它是如何发生的以及为什么会发生的例子。

具体来说,下面是我阅读的帖子的链接:
https://css-tricks.com/almanac/properties/m/margin/

清楚地解释了折叠是垂直发生的,并且它是出于某种目的而实现的。但是,有人提到

This does not happen on horizontal margins (left and right), only vertical (top and bottom).

没有解释为什么它不会发生在水平边距上。

为什么不发生水平边距折叠?

最佳答案

水平边距永远没有机会折叠,因为控制边距折叠的规则意味着它们永远无法满足条件。

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.

折叠边距 ( http://www.w3.org/TR/CSS21/box.html#collapsing-margins )

相邻的框只能是 block 级框:

Two margins are adjoining if and only if:

  • both belong to in-flow block-level boxes that participate in the same block formatting context

折叠边距 ( http://www.w3.org/TR/CSS21/box.html#collapsing-margins )

而且边距只有在没有 float 或绝对定位时才会折叠:

  • 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 absolutely positioned boxes do not collapse (not even with their in-flow children).

折叠边距 ( http://www.w3.org/TR/CSS21/box.html#collapsing-margins )

这意味着 block 级框永远不能水平放置在同一行(因为 block 级框默认会自动在新行开始)并同时满足边距折叠条件。

理论上,行内框可以满足条件,但由于它们不是 block 级的,所以规则根本不适用于它们。

In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes.

内联格式化上下文 ( http://www.w3.org/TR/CSS21/visuren.html#block-formatting )

也就是说,它们没有崩溃的原因很简单,W3C 是这么说的:

Horizontal margins never collapse.

折叠边距 ( http://www.w3.org/TR/CSS21/box.html#collapsing-margins )

关于html - 为什么水平边距不会像垂直边距一样折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32838027/

相关文章:

html - flexbox 中的统一汽车元素高度

CSS 过渡显示行内文本

css - DIV 打印时不分页

javascript - 合并多个样式表

javascript - 未捕获的 TypeError : UICtrl. getDOMstrings 不是函数

java - 如何禁用/避免 Java-XML 中的 Ampersand-Escaping?

html - 响应式网站无法在 Firefox 中运行

jquery - Portfolio Grid随机间距@media查询

html - 对使用固定表头构建表的示例感到困惑

javascript - 为什么我不能在 ie 中未插入的节点上使用原型(prototype) DOM 方法?