padding-top如何作为与父母宽度相关的百分比?

时间:2013-07-12 17:59:19

标签: css css3

以下是一个例子:

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

注意所有红色div是如何相同height并且padding-top:100%;,但它们是A& B具有不同的填充大小......并且看起来父的宽度会更改此值(请注意,C会更改父级的height,但这不会改变填充)。

为什么padding以这种方式与宽度相关?

编辑:由于历史原因,如果jsfiddle消失,我在我的例子中使用的代码如下......

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

5 个答案:

答案 0 :(得分:30)

来自CSS fluid layout: margin-top based on percentage grows when container width increases

  

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

Straight from the horse's mouth

'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
  

百分比:指包含块的宽度

答案 1 :(得分:1)

答案 2 :(得分:1)

填充百分比确实与宽度相关,但具体而言,padding: 100%也可以读作padding: *width-of-container*px

A C 块的宽度为70px。应用padding: 100%padding: 70px

相同

答案 3 :(得分:0)

元素的高度取决于其内容,其中包括其子元素的填充和边距,因此,如果子元素依赖于其父代高度,则会导致循环。

答案 4 :(得分:0)

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

padding-top: calc(.25 * 100vh);