input的width为100%超过父容器宽度的解决办法

2023-04-16阅读:2495

先上代码:

<style>
    .form-group{width:420px;}
    .form-group input{width:100%;padding:0 12px;line-height:34px;}
</style>
<div class="form-group">
    <input placeholder="padding..."/>
</div>


这段代码原本打算的是在form-group的放一个宽度为420px的input框。然而事与愿违。

width.png

可以看出真实的宽度是448(420 + 12 + 12 = 444),等等多出的4个像素是怎么回事啦。猜想是边框的像素值,把input加上border: 1px solid;则input宽度变成了446。为了达到预期的效果,我把代码改了一下:

<style>
.form-group input{width:calc(100% - 24 - 4);padding:0 12px;line-height:34px;}
</style>


这样虽说解决了问题,但是肯定是走弯路了。后来想想,其实一句box-sizing: border-box;就可以解决的。


大家都爱看
查看更多热点文章