CSS Centering Vertically

The Solution For Modern Browsers

  1. set the display property of the parent element to table
  2. set the display property of the content element to table-cell. The content behaves much as an old-fashioned <td> element would… and setting vertical-align to middle
IE7 fails to support display:talbe this method, even in strict mode. Microsoft did not implement support fordisplay:tablein IE7.

The Solution For IE7

For IE7, we’ll three div elements instead of two. I’ll call them the “parent,” the “wrapper” and the “content.”

The first is the parent we wish to center in. The second acts as a wrapper around the content. We position this second element with its top edge vertically centered in the parent element ( top: 50% ).

The third element is the actual content… and position it negatively, subtracting half of its own height ( top: -50% ). This works because the second element – our “wrapper” element – does not have afixed height of its own. So it takes on the height of its content. That’s important because percentages always refer to the width or height of the containing element. So -50% gives us the desired result.

Here’s the complete solution for IE only

Why We Can’t Just Do It This Way All The Time

You might ask why we can’t use this clever solution in all browsers. It sounds good, doesn’t it! But there’s a catch.

The “50% solution” depends on the idea that the wrapper takes on the height of its content, and thattop: -50%will be calculated based on the height of the wrapper. However, the CSS2 specification says thatif the height of the containing block is not specified explicitly, then percentages are ignored.This avoids complicated situations where the height of the content is a percentage of the height of the parent – which depends on the height of the content!

So in a standards-compliant browser, like Firefox, the content doesn’t get moved up halfway to center on the middle. Only IE ignores this aspect of the standard.

One thought on “CSS Centering Vertically

  1. very nice!I wonder how many WP depoelvers can make it in just a few lines as well lol! I guess not many ;)bookmarking this page, I have a feeling it might come handy sometime!:)

Leave a Reply

Your email address will not be published. Required fields are marked *