Read more

Howto properly use vertical-align to align elements vertically

Dominik Schöler
May 22, 2012Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2012-05-22 16:34)