In html, how is a child element's percentage-based size calculated when its parent has padding?
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 someth开发者_开发技巧ing. 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.
I'm not sure exactly what you are trying to do, but why not create a separate class for each div, rather than starting out by styling just plain div? That way the inheriting won't interfere with what you want.
Here's a fiddle: http://jsfiddle.net/B3Mjt/
div.parent {
background-color:yellow;
padding-left:20px;
padding-right:20px;
width:200px;
height:200px;
}
div.child {
background-color:red;
width:100%;
height:50%;
}
精彩评论