我有一个html输入。

输入有填充:5px 10px;我希望它是100%的父div的宽度(这是流体)。

然而使用宽度:100%;导致输入为100% + 20px我怎么才能解决这个问题呢?

例子


当前回答

对我来说,使用margin:15px;padding:10px 0 15px 23px;width:100%,结果是这样的:

我的解决方案是使用width:auto代替width:100%。我的新代码是:

边距:15px;填充:10px 0 15px 23px;宽度:自动。然后元素正确对齐:

其他回答

你可以不使用box-sizing和不明确的解决方案,如width~=99%。

演示jsFiddle:

保持输入的填充和边框 添加到输入负水平边距= border-width +水平填充 在输入的包装器中添加与上一步的边距相等的水平填充

HTML标记:

<div class="input_wrap">
    <input type="text" />
</div>

CSS:

div {
    padding: 6px 10px; /* equal to negative input's margin for mimic normal `div` box-sizing */
}

input {
    width: 100%; /* force to expand to container's width */ 
    padding: 5px 10px;
    border: none;
    margin: 0 -10px; /* negative margin = border-width + horizontal padding */ 
}

Box-sizing: border-box是一个快速,简单的方法来修复它:

这将适用于所有现代浏览器和IE8+。

这里是一个演示:http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

在现代浏览器中不需要浏览器前缀版本(-webkit-box-sizing等)。

将输入框的填充移到包装器元素。

<style>
div.outer{ background: red; padding: 10px; }
div.inner { border: 1px solid #888; padding: 5px 10px; background: white; }
input { width: 100%; border: none }
</style>

<div class="outer">
    <div class="inner">
       <input/>
    </div>
</div>

参见示例:http://jsfiddle.net/L7wYD/1/

也使用百分比填充,并从宽度中删除:

padding: 5%;
width: 90%;

使用css calc()

超级简单,也非常棒。

input {
    width: -moz-calc(100% - 15px);
    width: -webkit-calc(100% - 15px);
    width: calc(100% - 15px);
}​

如图所示:Div宽度100%减去固定数量的像素 通过webvitaly (https://stackoverflow.com/users/713523/webvitaly) 原始来源:http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/

把这个复制到这里,因为我差点在另一个线程中漏掉了。