21

Here is an example:

http://jsfiddle.net/QZAd8/1/

Notice how all of the red divs are the same height and have padding-top:100%;, yet they A & B have different padding sizes... and it appears that the width of the parent changes this value (note that C changes the height of the parent, yet that doesn't alter the padding).

Why is padding related to width in this way?

Edit: for historical reasons, and in case jsfiddle goes away, the code I used in my example is as follows...

.outer {
  background-color: green;
  height: 300px;
  width: 70px;
  float: left;
  margin-right: 10px;
}

.middle {
  background-color: red;
  height: 100px;
  width: 50px;
  padding-top: 100%;
}

.inner {
  background-color: blue;
  height: 3px;
  width: 100%;
}
<div class='outer'>
  <div class='middle'>
    A
    <div class='inner'>
    </div>
  </div>
</div>

<div class='outer' style='width:100px'>
  <div class='middle'>
    B
    <div class='inner'>
    </div>
  </div>
</div>

<div class='outer' style='height:400px'>
  <div class='middle'>
    C
    <div class='inner'>
    </div>
  </div>
</div>

4

5 回答 5

41

来自CSS 流体布局:当容器宽度增加时,margin-top 基于百分比增加

在 CSS 中,所有四个 margin: 和 padding: 百分比都是相对于宽度的......即使这看起来很荒谬。这就是 CSS 规范的方式,你无能为力。

直接从马嘴里说

'padding-top', 'padding-right', 'padding-bottom', 'padding-left'
Value:      <padding-width> | inherit
Initial:    0
Applies to:     all elements except table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column
Inherited:      no
Percentages:    refer to width of containing block
Media:      visual
Computed value:     the percentage as specified or the absolute length

百分比:指包含块的宽度

于 2013-07-12T18:06:57.500 回答
1

只是因为它应该是这样的:) http://www.w3.org/TR/CSS2/box.html#propdef-padding-top

于 2013-07-12T18:12:23.693 回答
1

填充百分比确实是相对于宽度而言的,但具体来说,padding: 100%也可以读作padding: *width-of-container*px.

A块和C块的宽度为70px. 申请padding: 100%是一样的padding: 70px

于 2013-07-12T18:16:58.737 回答
0

元素的高度取决于其内容,包括其子元素的内边距和边距,因此如果子元素依赖于其父元素的高度,这将是一个循环。

于 2019-05-12T04:43:39.857 回答
0

如果您像我一样来这里寻找替代方案,您可以使用 CSS 计算将 padding-top 设置为垂直高度的百分比:

padding-top: calc(.25 * 100vh);
于 2020-05-28T20:35:26.287 回答