How can I vertically center a “div” element for all browsers using CSS?

Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari.

.outer {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

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

.inner {
  margin-left: auto;
  margin-right: auto;
  width: 400px;
  /* Whatever width you want */
}
<div class="outer">
  <div class="middle">
    <div class="inner">
      <h1>The Content</h1>
      <p>Once upon a midnight dreary...</p>
    </div>
  </div>
</div>

 Run code snippetExpand snippet

View A Working Example With Dynamic Content

I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also — lightbox, pop-up, etc.

Leave a Comment