这是一个例子:
请注意所有红色 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/17621181/