In html, how is the percentage size of a child element calculated when its parent has padding calculated?

advertisements

In the following example, the outer yellow box is 240px wide (width of 200 plus padding of 20 on left and right).

Its red child has width set to 50%. If you measure the red box as rendered, its width is 140px. See here.

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

If I set the child's width to 100%, the child ends up being 240px wide. See here.

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.

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.

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%;
}

Thanks!


makes perfect sense (jk). It's because the child div is inheriting the parent's padding.