Style input element to fill remaining width of its container

Viewed 258907

Let's say I have an html snippet like this:

<div style="width:300px;">
    <label for="MyInput">label text</label>
    <input type="text" id="MyInput" />
</div>

This isn't my exact code, but the important thing is there's a label and a text input on the same line in a fixed-width container. How can I style the input to fill the remaining width of the container without wrapping and without knowing the size of the label?

9 Answers

as much as everyone hates tables for layout, they do help with stuff like this, either using explicit table tags or using display:table-cell

<div style="width:300px; display:table">
    <label for="MyInput" style="display:table-cell; width:1px">label&nbsp;text</label>
    <input type="text" id="MyInput" style="display:table-cell; width:100%" />
</div>

If you're using Bootstrap 4:

<form class="d-flex">
  <label for="myInput" class="align-items-center">Sample label</label>
  <input type="text" id="myInput" placeholder="Sample Input" class="flex-grow-1"/>
</form>

Better yet, use what's built into Bootstrap:

  <form>
    <div class="input-group">
      <div class="input-group-prepend">
        <label for="myInput" class="input-group-text">Default</label>
      </div>
      <input type="text" class="form-control" id="myInput">
    </div>
  </form>

https://jsfiddle.net/nap1ykbr/

The answers given here are a bit outdated. So, here I'm with the easiest solution using modern flexbox.

.input-container{
display:flex;
}
input{
flex-grow: 1;
margin-left: 5px;
}
<div style="width:300px;">
    <div class="input-container">
    <label for="MyInput">label text: </label>
    <input type="text" id="MyInput"/>
    </div>
    
    <div class="input-container">
    <label for="MyInput2">Long label text: </label>
    <input type="text" id="MyInput2" />
    </div>
    
</div>

Related