【发布时间】:2012-06-15 18:19:14
【问题描述】:
如果您查看CSS box model spec,您会看到以下内容:
[margin] 百分比是相对于生成框的包含块的宽度 计算的。 请注意,'margin-top' 和 'margin-bottom' 也是如此。 如果包含块的宽度取决于此元素,则结果布局在 CSS 2.1 中未定义。 (强调我的)
确实如此。但是为什么?到底是什么迫使任何人以这种方式设计它?很容易想到您想要的场景,例如某件事总是从页面顶部向下 25%,但是很难想出任何理由让您希望垂直填充相对于父级的水平大小。
这是我所指的现象的一个例子:
<div style="border: 1px solid red; margin: 0; padding: 0; width: 200px; height: 800px;">
This div is 200x800.
<div style="border: 1px solid blue; margin: 10% 0 0 10%;">
This div has top-margin of 10% and left-margin of 10% with respect to its parent.
</div>
</div>
【问题讨论】:
-
我最初的想法是它会导致
margin: 25%的实际含义模棱两可。即使代码表明是这样,它也不会是一个均匀的边距。我没有证据支持这一点,但这似乎是合理的。 -
jsFiddle of my thoughts。高度比宽度更易变化,因此每当内容发生变化时,它会使边距以难以预测的方式移动。
-
@Ryan:是的,这不会是一个均匀的边距,但话又说回来,如果你说
height: 10%; width: 10%,你也不会得到一个正方形元素。 -
根据dev.w3.org/csswg/css3-box/#the-margin-properties 声明
Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).所以它是双向的 -
@Ryan 我认为我们有赢家。在这里寻找演示 - jsFiddle