Getting HTML textarea controls to expand to width

2020-07-11 07:44发布

问题:

I want my textarea controls to follow standard block display layout behavior, so that they expand to the width of the containing parent. Simply setting display:block; won't do this- they default to some default with value. Setting width:100%; doesn't work because any padding in the controls means they spill over the container bounds.

HTML:

<div class='container'>
    <div >test</div>
</div>
<div class='container'>
    <textarea >test</textarea>
</div>​

CSS:

.container {
    width:300px;
    border:black solid 1px;
    margin:10px;
}
.container > div {
    display:block;
    padding:10px;
    background:red;
}
.container > textarea {
    display:block;
    padding:10px;
    background:red;
}

RESULT:

http://jsfiddle.net/hKcjc/

回答1:

You can use the css3 property called box-sizing to solve this: http://jsfiddle.net/QK78b/

Add the following:

width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; 

See Box Sizing | CSS-Tricks for an explanation of this issue and how it relates to TextAreas