htmlcssalignmentvertical-alignmentcentering

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


I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.

<body>
    <div>Div to be aligned vertically</div>
</body>

How can I center a div vertically in all major browsers, including Internet Explorer 6?


Solution

  • 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>

    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.