Vertically centering a box in a web page is a widespread coding problem. There are many, many solutions out there. Today I’ll present you a modified version of the ‘horizon’ technique.
The ‘horizon’ technique, as I call it, includes an absolutely positioned div to the vertical center of the web page. Inside it’s nested the target box of a desired size. The classic implementation has a certain drawback – if the size of the box is greater than the visible area the browser do not present scrolls. So the content got cropped out. Most of the time this is not a problem. Obviously this is not our case. So let’s dive.
The horizon
As mentioned before the horizon is div
absolutely positioned across the page:1
2
3
4
5
6#horizon {
position: absolute;
top: 50%;
width: 100%;
height: 1px;
}
And this is what it looks like: step 1. Oh, no! There is a horizontal scroll. This is because we wanted out horizon to span all across the page at 100% not taking into account the margins of the body. Here is the simple fix:1
2
3
4
5
6
7
8
9
10body {
padding: 0;
}
#horizon {
position: absolute;
width: 100%;
height: 1px;
top: 50%;
}
Now it looks like it should be: step 2.
This will hold our box at 50% of the height of the body. Now let’s add the box to the scope.
The box
Now that our horizon is ready we need our content container in it. I’ll call it simple ‘scene’:1
2
3
4#scene {
width: 750px;
height: 450px;
}
The scene is 750px in width and has 450px height: step 3. As you can assure yourselves the box is not even close to the center. Let alone vertically. Here is how we’ll manage it:1
2
3
4
5#scene {
width: 750px;
height: 450px;
margin: -225px auto auto auto;
}
And we’re ready step 4!
Ready
That was really close. All normal browsers (Firefox 2+, Chrome 4+, Opera 7+, Safari 3+) are working fine. Guess who’s wrong? IE6, right. The top part of our box is ruthlessly cut off by the horizon. So far we could do it without hacks. Thankfully, the fix is rather simple. And here it is:1
2
3
4
5
6#scene {
width: 750px;
height: 450px;
margin: -225px auto auto auto;
position: relative; /* IE6 fix */
}
I have to note here that IE7+ works just like is expected and renders the page correctly. Here is the final step 5 normalized for IE6.