thegreatjedi thegreatjedi - 6 months ago 12
CSS Question

Vertically align label with input

I am currently converting an old HTML form to not use tables. The label requires a fixed width, which I've achieved using an answer from this site. The current code is as follows:

HTML

<div id="form">
<label for="field1">Name&nbsp;</label>
<input type="text" id="field1" value="default name" />
</div>


CSS

label {
float: left;
width: 50px;
white-space: nowrap;
}
input {
display: block;
overflow: hidden;
width: *;
}
#field1 {
width: 150px;
}


Currently, the label is vertically aligned at the top. How can I vertically align the label and field to the centre?

Edit: I'm getting a lot of answers to basically pad my label into the correct position via a specified number of pixels. I don't want to do that as it's basically hard-coding and not true vertical alignment to the middle.

Following some advice I've received here, I've cleaned up my code some. See the above edited code.

I've tried
vertical-align: middle;
in
label
but it doesn't work. Please note that the user's platform will be IE.

Answer

If I get this right, You want the label and the input to vertically center align W.R.T each other and not the page. For that, there are couple of ways.

The vertical-align Way

This works well when you have both the label and the input on one line as inline-block elements. Example -

.fieldHeading {
  width: 50px;
  vertical-align:middle;
}
.fieldSpan {
  overflow: hidden;
  vertical-align:middle;
}
#field1 {
  width: 150px;
}
<div id="form">
  <label for="field1" class="fieldHeading">Name&nbsp;</label>
  <span class="fieldSpan"><input type="text" id="field1" value="default name" /></span>
</div>

The height & line-height Duo

This works well too but if your label is big and has the possibility of wrapping into multiple lines, it's gonna look terrible. Example -

.fieldHeading {
  width: 50px;
}
.fieldSpan {
  overflow: hidden;
}
#field1 {
  width: 150px;
}

/*line-height and height be same for parent
* background added for clarity.
*/
#form {
  line-height: 40px;
  height: 40px;
  background: #bada55;
}
<div id="form">
  <label for="field1" class="fieldHeading">Name&nbsp;</label>
  <span class="fieldSpan"><input type="text" id="field1" value="default name" /></span>
</div>

The Flexbox Way

If you want to use something new from the CSS world and be future ready, use flexbox. Example -

.fieldHeading {
  width: 50px;
}
.fieldSpan {
  overflow: hidden;
}
#field1 {
  width: 150px;
}
/*flexbox approach.
* height and background added for clarity.
*/

#form {
  height: 100px;
  background: #bada55;
  display: flex;
  align-items: center;
}
<div id="form">
  <label for="field1" class="fieldHeading">Name&nbsp;</label>
  <span class="fieldSpan"><input type="text" id="field1" value="default name" /></span>
</div>

I hope these help you not only in this problem but for all other vertical alignment problems.