我有一个html输入。

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

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

例子


当前回答

使用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/

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

其他回答

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

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

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

把它包在容器里怎么样?容器应该有这样的风格:

{
    width:100%;
    border: 10px solid transparent;
}

这就是为什么我们在CSS中使用box-sizing。

我已经编辑了您的示例,现在它可以在Safari, Chrome, Firefox和Opera中工作。去http://jsfiddle.net/mathias/Bupr3/看看吧 我只是补充说:

input {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

不幸的是,旧的浏览器如IE7不支持这一点。如果您正在寻找一个适用于旧ie的解决方案,请查看其他答案。

你可以不使用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 */ 
}

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

<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/