使用box-sizing:border-box来计算百分比填充的奇怪行为: [英] Odd behavior calculating percentage padding with box-sizing:border-box;

查看:144
本文介绍了使用box-sizing:border-box来计算百分比填充的奇怪行为:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用小提琴来设置测试用例: http://jsfiddle.net/5M7X7/2/

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

我有一个宠物项目,展示了一些border-box布局.我看到分层块元素具有奇怪的行为(至今仍是跨浏览器一致的).

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

根据示例,共有3个div:第一个div具有固定的高度和宽度,其子级具有100%的高度和宽度,加上两侧的%填充,其子级具有100%的高度和宽度.

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.

使用宽度计算垂直填充.这是border-box的一些故意古怪吗?是否有使用css的布局技巧,使其表现出如我所愿"的效果,并使用高度来计算垂直填充?

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?

我不需要JS解决方法,也不需要采用其他方法来调整我最小的盒子的大小.我对这个特殊的布局怪癖,为什么会发生以及是否有一种纯净,简单的CSS方式使它表现"感兴趣,对此感兴趣.

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.

谢谢!

推荐答案

这实际上是CSS规范的一部分,因此此行为是正确的,应与您的期望保持一致.

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.

要对此做一点扩展,宽度计算取决于孩子的盒子模型;如果未指定,则孩子的宽度可能会超出父母的宽度.

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/

这篇关于使用box-sizing:border-box来计算百分比填充的奇怪行为:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆