Blog

Vertical Align a Div

One of current CSS left outs is vertical align div. And before CSS 3 comes we have to use some tricks to solve this problem. I looked over for some solutions and it all comes up to defining it as table and using vertical align. The second one appears a lot and it’s a nice solution, but it has two faults, I’ll tell you later about them, here’s the code first.

Idea is to place absolute div 50% left and top and then to move margin left and top half if it’s size.

Vector people

.wrapper {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}

Problem?

This works only with defined height and when div height is less then browser height so you can’t have scroll. Now you’ll ask why do anyone want vertical align when there’s a vertical scroll? Well for example you have container height 820px and you have it vertically centered in all larger resolutions, simple.

Solution

In this problem (when browser height is less than div height) at smaller resolutions 1/3 of div is not visible, it’s in negative top margin. So idea is to place some relative div that will prevent div to go into negative margin. Here is the code.

Content

html, body {
height: 100%;
margin: 0;
padding: 0;
}

* {
margin:0px auto;
padding:0;
}

div#shim {
visibility: hidden;
width: 100%;
height: 50%;
margin-top: -200px;
float: left;
}

div#wrapper {
width: 1000px;
height: 400px;
clear: both;
background:red;
position: relative;
top: -200px;
/* IE4ever Hack: Hide from IE4 **/
position: static;
/** end hack */

}

/* Hide from IE5mac \*//*/
div#shim {
display: none;
}

html, body {
height: auto;
}
/* end hack */

/* ]]> */

Only fault is again defined height and it can’t be solved with CSS, not right now, I hope new version will or some JS fix. Click here for demo