根据W3C规范,box-sizing: border-box应在宽度/高度内绘制填充.这意味着padding不应该增加该元素的宽度.
然而,我现在遇到一个奇数的情况下的填充是实际上增加宽度,后一个神秘阈:
div {
display: inline-block;
width: auto;
}
input {
display: block;
width: 100%;
box-sizing: border-box;
padding: 0;
}
#a {
padding-right: 84px;
}
#b {
padding-right: 100px;
}Run Code Online (Sandbox Code Playgroud)
<div>
<span>No padding</span>
<input />
<input />
<span>Foo bar this determines the space</span>
</div>
<hr>
<div>
<span>84px of padding</span>
<input />
<input id="a" />
<span>Foo bar this determines the space</span>
</div>
<hr>
<div>
<span>100px; width expands ?!?!</span>
<input />
<input id="b" />
<span>Foo bar this determines the space</span>
</div>Run Code Online (Sandbox Code Playgroud)
单击运行代码段并向下滚动以查看问题.<input>s 的宽度应为214px,但设置超过84px的填充会开始增加宽度.为什么会发生这种情况,我该如何预防呢?
这意味着
padding不应该增加该元素的宽度.
不完全正确.如果在从外部宽度减去填充之后,剩余的内部宽度为负,则将其钳位为零,因为它不能为负.
因此,是的,添加填充可以增加框的外部宽度.
但是,您的情况很有趣,因为外部宽度的增量发生在可能的预期之前.
会发生的是有一个内联块容器width: auto.这意味着它的宽度将是缩小到适合/适合内容的大小.那是,
因此,其宽度取决于内容的宽度贡献.
然后width: 100%在内联块内部有一个输入宽度.
该百分比应该相对于包含块(内联块)的宽度来解决,但这是一个循环定义!
因此,宽度不明确.在那种情况下,CSS Sizing说
对于替换元素,最小内容大小和最大内容 大小是等效的,并且对应于 元素的默认大小调整算法 [CSS3-IMAGES] 返回的具体对象大小的适当维度,使用无约束的指定大小计算.
该算法返回替换元素的固有宽度.
每个轴的最小内容贡献和最大内容贡献是元素在该轴上指定的外部大小,如果确定的话; 否则,它们是上面指定的最小内容大小,加上该轴[...]中元素的边距/边框/填充.
也就是说,内联块的宽度至少是输入的固有宽度加上其填充.
知道该宽度后,可以解析输入的百分比.
那么,让我们说吧
xyz假设有足够的可用空间,内联块(和输入)的宽度将是max(x, y+z).
因此,增加填充z不会影响结果宽度if x >= y+z.但是一旦到达x == y+z,结果宽度将随着填充而增加.
您可以通过使用确定的宽度而不是百分比来避免此行为,并使用min-width以达到所需的百分比宽度.
input {
width: 0; /* Ignore intrinsic width */
min-width: 100%; /* Instead of width */
}
Run Code Online (Sandbox Code Playgroud)
div {
display: inline-block;
width: auto;
}
input {
display: block;
width: 0; /* Ignore intrinsic width */
min-width: 100%; /* Instead of width */
box-sizing: border-box;
padding: 0;
}
#a {
padding-right: 84px;
}
#b {
padding-right: 100px;
}Run Code Online (Sandbox Code Playgroud)
<div>
<span>No padding</span>
<input />
<input />
<span>Foo bar this determines the space</span>
</div>
<hr>
<div>
<span>84px of padding</span>
<input />
<input id="a" />
<span>Foo bar this determines the space</span>
</div>
<hr>
<div>
<span>100px; width expands ?!?!</span>
<input />
<input id="b" />
<span>Foo bar this determines the space</span>
</div>Run Code Online (Sandbox Code Playgroud)