May 22 2009

Vertical & Horizontal Centering w/ 3 lines of CSS

This method has become our ‘gold standard’ for centering your sites, images, or anything directly in the center of the page (vertically and horizontally).  It’s easy to use, unobtrusive to your other page elements, requires only 3 lines of CSS and no javascript.  It’s almost like a CSS plugin of sorts.   The only downside is that 3 div elements are required, however, compared to all other solutions we’ve tested, this is minimal overhead, and worth the effort.    It’s built on Jakpsatweb’s method for Vertical Centering in CSS. Compatibility:

“The code below works in Internet Explorer 5.0, 5.5 and 6.0, in Gecko browsers (Mozilla, Firefox, Netscape 7), in Opera 7, Konqueror 3.3.1. (maybe lower too), and in Safari. The page can be HTML or XHTML, standard or quirk mode.

Both examples don’t work in IE 5.2 for Mac. As I haven’t Mac, I can’t test it. Please let me know (dusan@pc-slany.cz) when you’d find any workaround.”

Vertical Centering Using CSS

1. Add 3 Classes to Your Stylesheet

.ht1 {display: table; #position: relative; overflow: hidden;width:100%;height:100%}
.ht2 {#position: absolute;  #top: 50%;display: table-cell; vertical-align: middle;text-align:center;}
.ht3 {#position: relative;  #top: -50%;margin:0 auto 0 auto;border:1px solid green;width:300px;height:200px}

Update: To clear up some confusion – we’ve added the widths & heights as needed above.  We had left them out to allow you to customize your own layout, but this way everything is included, and you can change the widths & heights as needed for your installation.

2. Create 3 elements in your HTML

<div class="ht1">
    <div class="ht2">
        <div class="ht3"></div>
    </div>
</div>

Important to Note:

ht1 =Is the main container, this div will be 100% width & height in size, positioned absolutely to the top left.

ht2 = 2nd container needed for vertical centering & positioning.

ht3 = Container to center. This needs an exact px width & height.

3. Set the Height & Width of ‘ht3′ Element.

In order to allow for reusability, we haven’t given this element it’s height or width, you will need to do so.  In most cases you will give these elements multiple css classes, that second class is most likely where you will define your height and width.

Voila – vertical & horizontal centering using 3 css classes.  Kinda makes me feel like riverdancing.