在HTML中,当子元素的父元素具有填充时,如何计算子元素的基于百分比的大小? [英] In html, how is a child element's percentage-based size calculated when its parent has padding?
问题描述
在下面的示例中,外部黄色框是240像素宽(宽度为200加上左边和右边的填充为20)。
In the following example, the outer yellow box is 240px wide (width of 200 plus padding of 20 on left and right).
其红色子项的宽度设置为50%。如果你测量红色框作为渲染,它的宽度是140px。请参阅此处。
Its red child has width set to 50%. If you measure the red box as rendered, its width is 140px. See here.
我是不知道该值是如何计算的。看来,要尊重父的填充,孩子的宽度应该是100(200的50%是100)。或者,如果在计算中包括填充,则应该是120(240的50%是120)。我不能到140 ...
I'm not sure how that value is calculated. Seems that to respect the padding of the parent, the child's width should be 100 (50% of 200 is 100). Or, if padding is included in the calculation, it should be 120 (50% of 240 is 120). I can't get to 140...
如果我将孩子的宽度设置为100%,那么孩子的宽度为240像素。请参阅此处。
If I set the child's width to 100%, the child ends up being 240px wide. See here.
这表示该填充确实包括在计算中(240的100%是240)。好的,50%应该产生120(240的50%是120),但它不是。
This would indicate that padding is indeed included in the calculation (100% of 240 is 240). Ok, then 50% should yield 120 (50% of 240 is 120), but it doesn't.
因此,根据我的浏览器,240的100% 240,240的50%为140。
So, according to my browser, 100% of 240 is 240 and 50% of 240 is 140. DOH!
我必须缺少某些东西。
I must be missing something. I'm sure there's a formula involved, but I can't find it documented.
这里是有问题的CSS样式:
Here are the CSS styles in question:
div {
background-color:yellow;
padding-left:20px;
padding-right:20px;
width:200px;
height:200px;
}
div.child {
background-color:red;
width:50%;
height:50%;
}
谢谢!
推荐答案
完美的意思(jk)。这是因为子div继承了父对象的填充。
makes perfect sense (jk). It's because the child div is inheriting the parent's padding.
这篇关于在HTML中,当子元素的父元素具有填充时,如何计算子元素的基于百分比的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!