Maarten Wolfsen Maarten Wolfsen - 2 months ago 8
CSS Question

Let form fill rest of the width

My code: https://jsfiddle.net/sf4g3v9n/

I want the input to fill the remaining space. I have searched this site quite a bit, but couldn't find a fitting answer.

Important: the text on the right is dynamic, so there is no absolute width.

My HTML structure:

<div class="container">
<form>
<div class="input-box">
<input type="text" placeholder="search..." />
</div>
</form>
<div class="selector">
<p>
dynamic content
</p>
</div>
</div>

Answer

You can do this using a flexbox like this:

* {
  margin: 0;
  padding: 0;
}

.container {
  width: 700px;
  display: flex;
}

form {
  float: left;
  flex: 1;
}

form .input-box{
  width: 100%;
  display: flex;
}

form input {
  padding: 10px 15px;
  font-size: 18px;
  width: 100%;
}

.selector {
  float: right;
}

.selector p {
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 10px 15px;
  font-size: 20px;
}
<div class="container">
  <form>
    <div class="input-box">
      <input type="text" placeholder="search..." />
    </div>
  </form>
  <div class="selector">
    <p>
      dynamic content
    </p>
  </div>
</div>

Because you want the input to fill in the remaining space, a flexbox is a natural option because that is what it is exactly for!

So here are the changes I did to your code:

  1. First I made your container a flexbox by doing this- which allows the form and the input-box to stay in the same row.

    .container {
      width: 700px;
      display: flex;
    }
    
  2. Added flex: 1 to your form to let it stretch to the remaining space.

  3. Flexbox 'flexing' is applied to the immediate children of the container for which you give display: flex. So you have to declare your inner div input-box as a flex container too.

  4. Now set the input box's width to 100% and there you go!

Cheers!