Ucodia
Ucodia

Reputation: 7700

Keep label and auto sizing input on the same line

I have a simple form with labels and inputs. I want the labels to appear on the left and the fields on the right to fill available horizontal space. All this no fixed sizes and no JavaScript.

Seemed like a simple task but I was not able to achieve it. Or I get them on the same line but the input does not fill the space or I get the input to fill available space but they appear on different lines...

Here is the example where I demonstrate the latter result which is the best I got so far:

HTML

<div class='form'>
  <div class='field'>
    <label>Name</label>
    <input/>
  </div>
  <div class='field'>
    <label>Description</label>
    <input/>
  </div>
</div>

CSS

.form {
    margin: 32px;
    padding: 16px;
    background-color: #eee;
}

.field * {
    display:inline-block;
}

.field label {
    width: 100px;
}

.field input {
    width: 100%;
}

JSFiddle: https://jsfiddle.net/Ucodia/9659vzhe/

Thanks for helping :)

Upvotes: 0

Views: 763

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

Maybe you can display them as a table. This will work well if your labels are short. You might have some side effect. A longer label (> 100px) will cause the text to wrap and the label to grow vertically. This will probably cause the input to grow with it, which might look weird. Apart from that, this is pretty solid.

.form {
    margin: 32px;
    padding: 16px;
    background-color: #eee;
}

/* The container is the table. It defines the space around the inputs */
.field {
    display: table;
    width: 100%;
    border-spacing: 0 5px;
}

.field * {
    display:table-cell;
}

.field label {
    width: 100px;
}

.field input {
    width: 100%;
}
<div class='form'>
  <div class='field'>
    <label>Name</label>
    <input/>
  </div>
  <div class='field'>
    <label>Description</label>
    <input/>
  </div>
</div>

Upvotes: 1

Related Questions