Make HTML input stretch to fill space in container

va. picture va. · Mar 8, 2013 · Viewed 19.1k times · Source

There is a <div id="MyDiv"> element which is resized depending on page width. It contains <input> and <a> elements.

How can I make the <a> align by the right side of the <div> and the <input> stretch to fit the free space between <div>'s left side and <a>'s right side?

Also the <a> should not jump to the next line and there are also defined min-width and max-width on the container. Here is the code:

<div id="MyDiv" style="background:#AAAAAA; width:100%; min-width:300px; max-width:600px;">
    <input type="text" id="MyInput"/>
    <a id="MyButton" href="#">Button</a>
</div>

and demo.

Answer

andyb picture andyb · Mar 8, 2013

This can be done easily with CSS3 although it will not work in IE9 or below. IE10 is the first Internet Explorer version to support the standard. The other browsers already support the relevant Flexible Box properties.

div {
  background: #AAAAAA;
  width: 100%;
  min-width: 300px;
  max-width: 600px;
  display: -webkit-flex;
}

input {
  -webkit-flex: 1;
}

a {
  margin: 0 10px;
}
<div>
  <input type="text" />
  <a href="#">Button</a>
</div>