Howto properly use vertical-align to align elements vertically

Updated . Posted . Visible to the public. Deprecated.

We have card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.

Say you want to vertically align a div box inside a div container. This is how you do it:

HTML

<div id="container">
  <div class="box">
    <span> Some text...<br />in two lines. </span>
  </div>
</div>

CSS

Set the line-height to the container's (implicit) height. The container MUST have a height >= its line-height, because the line-height actually spans the area inside which .box will align vertically.

#container {
  line-height: 50px;
}

Because the container's line-height is inherited by .box, reset it to a normal value now. You may use the (browser dependent) default value 'normal'. Omit display: inline-block; for elements that already are inline elements (e.g. a span).

.box {
  vertical-align: middle;
  line-height: 1.1em;
  display: inline-block;
}

Also see How to make a single check box (or image, etc) align vertically.

Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2012-05-22 14:34)