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?
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 working 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.
Without an "absolute" outer DIV, any content on the page before it will push the whole block down. This makes it more independent of other page content.
.outer {position:absolute;width:100%;height:100%}
is not necessary, they are here simply for demonstrating. All we need isdisplay:table
, if anyone is confused as I was.I've noticed that this needs 99% to avoid scroll bars. More important, this works with only the first two divs, say keep
.outer
andmiddle
and plainly ignore the.inner
and its style. I don't know what is the point ofmargin-left
,margin-right
set to auto since that doesn't center the element horizontally??!!!Removing
width: 100%;
and addingmargin: 0 auto
to.outer
allows variable width as well.It's 2020 and we no longer need hacks like this for vertical centering. Just use flexbox on the parent element. It even works in IE11!
.outer { display: flex; justify-content: center; align-items: center; height: 400px}
(note that vertical centering always requires a finite height for the parent element)