Odd behavior calculating percentage padding with box-sizing:border-box;

。_饼干妹妹 提交于 2020-01-05 12:10:40

问题


Used fiddle to set up test case: http://jsfiddle.net/5M7X7/2/

I have a pet project flexing some border-box layouts. I'm seeing an odd (yet cross-browser consistant) behavior with layered block elements.

As per the example, there are 3 divs: first one has a fixed height and width, its child has 100% height and width, plus a % padding on two sides, and its child is 100% height and width.

The vertical padding is being calculated using the width. Is this some intentional quirk of border-box? Is there a layout trick using css to make it behave "as I would expect", using the height to calculate vertical padding?

I don't need the JS workaround, nor a different way to size my littlest box. I'm interested in this particular layout quirk, why it's happening, and if there's a pure, simple css way to make it "behave".

EDIT Apparently, the padding % is calculated as a percentage of width, regardless of which box-sizing you're using. I have never in all my years as a front-end developer run into this before. If anyone knows a good workaround, I'm all ears.

Thanks!


回答1:


This is actually part of the CSS spec, so this behavior is correct and should be consistent with what you expect.

If you want an explanation as to why, they don't actually provide one, but it's speculated that it's because parent height depends on child height, and child height would be affected by the percentage padding.

EDIT: To expand on this a little bit, the width calculation is not dependent on the box model of the child; the child's width can grow out of the parent if neither is specified.

span, div {
    display: inline-block;
    border: 1px solid black;
}
span span {
    padding: 50%;
}
<span><span>foon</span></span>
<div><div>foon</div></div>

http://jsfiddle.net/XHDEL/



来源:https://stackoverflow.com/questions/15693480/odd-behavior-calculating-percentage-padding-with-box-sizingborder-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!