输入文本框宽度与父级相同

rhy*_*rhy 7 html css

我怎样才能有一个继承其容器宽度的文本框?

例如,我有一个div,里面有一个文本框.

<div id='content' style='width:100%;'>
    <input type='text' name='txtUsername'>
</div>
Run Code Online (Sandbox Code Playgroud)

我想要做的是当我调整浏览器大小时,文本框必须遵循它的父div的宽度.

使用上面的代码,每当我将浏览器调整为较小的宽度时,文本框总是溢出它的容器.

kea*_*ine 12

你应该box-sizing:border-boxwidth:100%.一起使用.这种方式input适合容器宽度的100%但不会因为添加input的填充而溢出:

#content input
{
    width:100%;
    box-sizing:border-box;
    -moz-box-sizing:border-box;
}
Run Code Online (Sandbox Code Playgroud)

现场演示:http: //jsfiddle.net/745Mt/1/

有关box-sizingCSS属性的更多信息,请参见示例:http://css-tricks.com/box-sizing/