Sunday, October 21, 2012

How To Setup Vertical Centered Labels With One Or Two Lines

The Problem

You try to style a form where you have labels with a fixed width. In some cases this leads to more than one line. You could define an individual style for each label. But this solution is very costly and it crashes if you need multilingual support because different languages may lead to different numbers of lines.

The Solution

There is an easy css-trick to get this behavior. You can set vertical-align: middle; in order to center the label. The vertical-align property requires the label to be wrapped into a div which is displayed as table. The label-tag itself has to be displayed as table-cell.

Example

CSS

.labelWrapper {
    display: table;
    float: left;
    height: 40px;
    line-height: 20px;
    margin: 3px 0; /*input border+padding*/
    width: 100px;
}

label {
    display: table-cell;
    vertical-align: middle;
}

input {
    height: 40px;
    padding: 2px 20px;
}

HTML

<form action="#" method="GET">
  <div class="fieldWrapper">
    <div class="labelWrapper">
      <label for="id_name">Name</label>
    </div>
    <input id="id_name" name="name" type="text">
  </div>
  <div class="fieldWrapper">
    <div class="labelWrapper">
      <label for="id_honorific_prefixes">Honorific Prefixes</label>
    </div>
    <input id="id_honorific_prefixes" name="honorific_prefixes" type="text">
  </div>
</form>