填充百分比是如何工作的?

11

HTML

<div class='wrapper'>
    <div class='elementContainer'>
        This line should start halfway down the yellow box
    </div>
</div>

CSS

.wrapper
{
    position: relative;

    height: 300px;
    width: 400px;

    background: lightyellow;
    border: 1px solid black;
}

.elementContainer
{
    position: relative;
    height: 200px;
    width: 300px;

    padding-top: 50%;

    background: red;
}
Fiddle示例:http://jsfiddle.net/jakelauer/s2ZXV/ 在上面的示例中,.elementContainer 有一个上内边距为 50%。这个值应该是基于父元素(.wrapper)的高度计算的,也就是说应该是 150px。但实际计算出来却是 200px。发生了什么问题呢?

显然,这是被计算为.elementContainerpadding-top: 50% - Robert Harvey
...是的,那就是我写的。 - Jake
我认为您可能误读了文档。文档指出百分比是基于“包含块”,而不是包含块的父元素。 - Robert Harvey
在这种情况下,它应该只有100px,因为包含块的高度为200px - Jake
好的,文档还指出它是基于宽度的,而在你的情况下是.wrapper中的400。请参见https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top - Robert Harvey
请参考此处的替代方案:https://dev59.com/qm445IYBdhLWcg3wNXg_。 - Robert Harvey
1个回答

17

这些规范解释了为什么。

<百分比>
百分比是相对于生成的框的包含块的宽度计算的。

400的50%是200。


使用box-sizing: border-box;属性计算元素宽度时不包含外边距。 - Alex78191

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接