Easy Vertical Centering with CSS
Thursday, May 15th, 2008It’s always good when you learn something that you already knew isn’t it?
I know that probably doesn’t quite make sense but what I mean is that quite often you know how things work but it’s how they are applied that can make all the difference. This is the beauty with CSS where you can always be surprised at the different ways the same layout can be achieved. This happened to me the other week when I noticed a different way that a site had been centered using simple techniques already known to us all. Indeed, many of you may already have used this method but it seems to have escaped my attention until now.
The Old Way
One of the first things I learned to do in CSS was how to horizontally and vertically center a fixed width and height element. This could be an image for a splash page (god forbid) or a small centered site that some designers love to do. Originally this was accomplished with absolutely positioning an element 50% from the top and 50% from the left of the viewport. This of course only places the top left corner of the element at the center of the viewport and you then need to drag the element back into a central position with a negative margin equal to half the height and half the width of the element.
Let’s take a look at the old way of doing this and note what the problems are.