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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)