How do I make an input element occupy all remaining horizontal space?
Here's the code:
<div style="width:400px">
some text..
<input type="text" />
<button value="click me" />
</div>
How can I make the input element expand to fill all the remaining space, while staying on the same line? If I put 100% it goes to a line o开发者_开发百科f its own...
See: http://jsfiddle.net/thirtydot/rQ3xG/466/
This works in IE7+ and all modern browsers.
.formLine {
overflow: hidden;
background: #ccc;
}
.formLine input {
width: 100%;
}
.formLine label {
float: left;
}
.formLine span {
display: block;
overflow: hidden;
padding: 0 5px;
}
.formLine button {
float: right;
}
.formLine input, .formLine button {
box-sizing: border-box;
}
<div class="formLine">
<button>click me</button>
<label>some text.. </label>
<span><input type="text" /></span>
</div>
The button
must go first in the HTML. Slightly distasteful, but c'est la vie.
The key step is using overflow: hidden;
: why this is necessary is explained at:
- http://colinaarts.com/articles/the-magic-of-overflow-hidden/#making-room-for-floats
- How does the CSS Block Formatting Context work?
The extra span around input
is necessary because display:block;
has no effect for input
: What is it in the CSS/DOM that prevents an input box with display: block from expanding to the size of its container
If you want a cross-browser decision you can use table
<table>
<tr>
<td>some text</td>
<td><input type="text" style="width:100%" /></td>
<td><button value="click me" /></td>
</tr>
</table>
If you can't use table it would be more difficult. For instance, if you know exactly the width of the some text you can try this way:
<div style="padding:0px 60px 0px 120px;">
<div style="width:120px; float:left; margin:0px 0px 0px -120px;">some text</div>
<input type="button" style="width:50px; float:right; margin:0px -55px 0px 0px;" />
<input type="text" style="width:100%;" />
</div>
If you don't care about old browsers support (IE <= 9) use a flexbox layout:
div{
background-color: red;
display: flex;
display: -webkit-flex;
display: -ms-flex;
display: -moz-flex;
flex-wrap: wrap;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
-moz-flex-wrap: wrap;
}
div input {
flex: 1;
-webkit-flex:1;
-ms-flex: 1;
-moz-flex: 1;
min-width: 200px;
}
精彩评论