Chris Chris - 5 months ago 16
CSS Question

vertically center div when body height: 100% without absolute pos

I have this to fill the window:

html, body {
height: 100%;}


then a container also set to height: 100%, how do I vertically center a div with an image without specifying and set height in pixels and without using absolute positioning? Using padding-top: 50%; padding-bottom 50%; isn't working - seems to shift the div depending on device site or browser window.

Answer

You can use display:table and display:table-cell:

html, body {
    width: 100%;
    height: 100%;
}

body{
    margin: 0;
    display: table
}

body>div {
    display: table-cell; 
    text-align: center; /* horizontal */
    vertical-align: middle; /* vertical */
}
<div>
    <img src="http://paw.princeton.edu/issues/2012/07/11/pages/6994/C-beer.jpg" />
</div>

JSFiddle

More on display property .

Comments