
Posted on: 02/09/2009
There are many ways to center a site vertically, some work quite well while others have a few bugs in them. A lot of the methods rely on the browser window being the correct size or bigger than the height of the site. If it isn’t the top of the content is forced off the top of the page and no scrollbar appears, making some of the content unreadable and the site unusable.
All is not lost, this technique has been named the float clear method and in my opinion is the best solution for vertically centering a website to date, as it will not cut off the top of the content.
The biggest advantage is that it doesn’t need any big work arounds to get it to work on some browsers, the only one that is needed is the horizontal center fix for IE browsers, that would be needed anyway if you were centering a site horizontally. Also should the display area be to small the content simply sits at the top of the page and will not go off the top, making it one of the more usable ways to align a site vertically.
The disadvantage of this technique is that there will be an empty div at the top of the page, although compared to a few of the other methods this is a small disadvantage.
Firstly you need to set the html and body height to 100% and give them a margin and padding of zero, like this:
html, body {
height:100%;
margin:0;
padding:0;
}
If you are planning on having the site centered horizontally too then you will need to add this bit of code, which is a fix for some browsers.
body {
text-align:center;
}
Next comes the part of code that will center the site:
#vertical {
height:50%;
width:1px;
margin-bottom:-150px; /* half the wrappers height */
float:left;
}
#wrapper {
margin:0 auto; /* use if centering horizontally */
text-align:left; /* set text back to default if centering horizontally */
position:relative;
height:300px;
width:700px;
clear:left;
}
This works by setting the height of the vertical div to 50% minus half the size of the wrappers height, by floating this to the left and then using the clear:left; within the wrapper, the wrapper div is then pushed down underneath the vertical div, causing it to be vertically centered.
<div id="vertical"></div>
<div id="wrapper">
<!-- Place content here-->
</div>
There you have it a vertically centered site.
5 Comments
Thanks for writing this tutorial for me Diz, always so helpful
Great. Tried many different tutorials on this and this one is right on the mark.
webdesignpond.co.uk – da best. Keep it going!
Thanks
DingoDogg
I’ve just been here for 5 minutes and I have seen enough. This site rocks. And I think I will use a lot of the tutorials over here.
Kind regards from the Netherlands.
Thanks Dizi, I have tried loads of tutorials and this is the first one that works!