为什么CSS中的边距/填充百分比总是根据宽度计算? [英] Why are margin/padding percentages in CSS always calculated against width?

查看:276
本文介绍了为什么CSS中的边距/填充百分比总是根据宽度计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您查看 CSS框模型规范,您会观察到以下:

If you look at the CSS box model spec, you'll observe the following:


[margin]百分比是相对于生成的框的包含块的宽度计算的。 请注意,margin-top和margin-bottom也是如此。如果包含块的宽度取决于此元素,则在CSS 2.1中未定义生成的布局。 (强调我)

The [margin] percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1. (emphasis mine)

这确实是真的。但为什么?什么会迫使任何人这样设计?很容易想到你想要的场景,例如。一个确定的事情总是从页面的顶部25%,但很难找出任何理由,你想要垂直填充相对于父的水平尺寸。

This is indeed true. But why? What on earth would compel anyone to design it this way? It's easy to think of scenarios where you want, e.g. a certain thing to always be 25% down from the top of the page, but it's hard to come up with any reason why you would want vertical padding to be relative to the horizontal size of the parent.

以下是我所指的现象的例子:

Here's an example of the phenomenon I'm referring to:

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

http:// jsfiddle.net/8JDYD/

推荐答案

将我的评论转移到答案,因为它有逻辑意义。但是,请注意这是毫无根据的推测。

Transferring my comment to an answer, because it makes logical sense. However, please note that this is unfounded conjecture. The actual reasoning of why the spec is written this way is still, technically, unknown.


元素高度由$的高度定义。 b $ b个孩子。如果一个元素有padding-top:10%(相对于父级
height),这将影响父级的高度。由于子对象的
高度取决于父对象的高度,父对象的
高度取决于子对象的高度,所以我们将
的高度不准确,或无限循环。当然,这只有
影响偏移父===父,但仍然的情况。

Element height is defined by the height of the children. If an element has padding-top: 10% (relative to parent height), that is going to affect the height of the parent. Since the height of the child is dependent on the height of the parent, and the height of the parent is dependent on the height of the child, we'll either have inaccurate height, or an infinite loop. Sure, this only affects the case where offset parent === parent, but still. It's an odd case that is difficult to resolve.

更新:最后几句话可能不完全准确。叶元素(没有子元素的子元素)的高度对其上的所有元素的高度有影响,因此这会影响许多不同的情况。

Update: The last couple sentences may not be entirely accurate. The height of the leaf element (child with no children) has an effect on the height of all elements above it, so this affects many different situations.

这篇关于为什么CSS中的边距/填充百分比总是根据宽度计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆