Burak Erdem Burak Erdem - 6 months ago 8
CSS Question

How to vertically center a div for all browsers?

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?

Answer

Below is the best all-around solution I could build to vertically & horizontally center a fixed-width, flexible height content box. Tested and working for recent versions of FF, Opera, Chrome, & Safari, and MSIE 6+.

HTML

<div class="outer">
<div class="middle">
<div class="inner">

<h1>The Content</h1>

<p>Once upon a midnight dreary...</p>

</div>
</div>
</div>

CSS

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

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

.inner {
    margin-left: auto;
    margin-right: auto; 
    width: /*whatever width you want*/;
}

To accommodate for IE 7 & older, use a separate style sheet with these changes:

<!--[if lte IE 7]><link rel="stylesheet... /><![endif]-->;
.outer {
    display: inline;
    top: 0;
}

.middle {
    display: inline;
    top: 50%;
    position: relative;
}

.inner {
    display: inline;
    top: -50%;
    position: relative;
}

View A Working Example With Dynamic Content

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

Comments