css - padding-top 与父级宽度的百分比有何关系?

标签 css

这是一个例子:

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

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

为什么 padding 和 width 有这种关系?

编辑:由于历史原因,为了防止 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>

最佳答案

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

In CSS, all four margin: and padding: percentages are relative to the width ...even though that may seem nonsensical. That's just the way the CSS spec is, there's nothing you can do about it.

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

Percentages: refer to width of containing block

关于css - padding-top 与父级宽度的百分比有何关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57646000/

相关文章:

html - bool 计算属性为 false/true 时的 knockoutjs css 绑定(bind)值

css - 如何在 View 生成的列表中的最后一个 <li> 上添加 "last"类?

javascript - 包含外部 CSS 文件是否安全,或者是否会导致代码注入(inject)?

javascript - CSS 动画 .fadeOut() 和宽度

jquery - 如何使用 jQuery 指定通配符 (*) 以将颜色应用于所有子级(深层)?

javascript - 一旦 div 滚动到尽头,页面就会滚动

php - 并排显示图像 php 和 css

javascript - 如何为 div 制作倒曲线或边框半径

css - 我想水平对齐 <div> b 和 <div> a ,有没有简单的方法可以做到?

html - 将 ':focus' 样式应用于输入组