Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make input to fill the remaining width of label

I am trying to achieve the following in HTML:

  • input inside label element (rather not use ids and label for)
  • input should occupy 100% of whatever width is remaining

It shouldn't be that hard, but I've tried lots of approaches from other examples; using floats, overflow: hidden, limiting the height of surrounding elements, etc. Not having 100% width works too, but that's not an option.

The reason I rather not use label-for (which does work) is that there will be several identical input fields on the same page. They are rather complex so I create one manually and then clone it with jQuery N times, which then would break horribly if using IDs.

Basic starting point:

input {
  width: 100%;
}
<label>
  name:
  <input type="text" />
</label>

Prepared a fiddle here: https://jsfiddle.net/8uuhhcon/

like image 510
Setomidor Avatar asked Mar 13 '23 14:03

Setomidor


2 Answers

Try Flexbox

label {
  display: flex;
}

input {
  flex: 1;
}
<label>name:
  <input type="text" />
</label>
like image 112
Nenad Vracar Avatar answered Mar 16 '23 03:03

Nenad Vracar


If you can wrap name: into a span or so, like <span>name:</span>, you can try the CSS table.

label {
  width: 100%;
  display: table;
}
span, input {
  display: table-cell;
}
span {
  width: 1%; /*give a small value*/
  white-space: nowrap; /*prevent wrapping i.e. "user name"*/
  vertical-align: middle; /*or top/bottom as needed*/
}
input {
  width: 99%; /*give a large value*/
}
<label>
  <span>name:</span>
  <input type="text" />
</label>
like image 32
Stickers Avatar answered Mar 16 '23 04:03

Stickers