Vertical center in CSS

Sep. 4, 2007 No Comments Posted under: CSS

Yesterday a collogue asked me about vertically centering (centring) a div in CSS. Vertical align in CSS does not seem to be able to solve this too well, and I had previously assumed that the only way to achieve the desired effect was to use JavaScript to get the window height and then subtract half the height of the element you want to center.

This isn’t great and seems a little bit hacky. So I did some research and found a couple of solutions (solution one, solution two). These have been around for a long time, I guess I must have just missed them?!

These both work, although the second is slightly more solid than the first. In at attempt to understand them further I made a demo page or each method, which should explain how they work.

Absolute positioned div

The first example based on Hicksdesign’s solution uses a div positioned 50% down the page with a negative bottom margin, set to half the height of the element you want to center. The second uses the same technique but with only one element.

The problem with both these methods is that content is lost at the top of the element if you make the browser window too small.

Absolute positioned div method
Absolute positioned div method 2

Spacer div

This example based on d-graff’s idea uses a floated div with a height of 50% and again a negative bottom margin, set to half the height of the element you want to center. The content is then set to clear the floated element.

This seems to be more solid as it works nicely with scroll bars.

Spacer div method

One problem with both these methods is that the content in the centered div has to be known and set by the CSS. In order to have higher(taller) content you will have to use overflow auto (as in the examples). Or use JavaScript to mod the height in your CSS/HTML.

This entry was posted on Tuesday, September 4th, 2007 at 5:28 pm and is filed under CSS. You can leave a comment and follow any responses to this entry through the RSS 2.0 feed.

Leave a Reply