Center a div horizontally and vertically using CSS

October 18, 2010

A few days ago, I needed to center a mini site horizontally and vertically (don't you just love client requests?). It 's easy to tackle the horizontal axis using CSS:

<style>
    .hcenter {
        margin: auto;
        width: 320px;
        height: 240px;
    }
</style>
<div class="hcenter">Horizontally centered text</div>

On the contrary, I thought that CSS can't handle vertical centering (at least in a cross-browser compatible way) and a quick Google session ended fruitless as well. Instead, I wrote a small script to programmatically center the div inside the window. It took a couple of revisions to support resizing, eliminate flickering, ensure cross-browser compatibility, etc. but eventually I got it right.

Today though, I re-discovered an old trick:

<style>
    .center {
        position: absolute;
        width: 320px;
        height: 240px;
        top: 50%;
        left: 50%;
        margin-top: -120px;
        margin-left: -160px;
    }
</style>
<div class="center">Horizontal and vertical centered text is possible.</div>

Duh!

Update, 24 Oct 2010: Oh, there is a better way:

    line-height: ${height}px;

where ${height} is equal to the height of the container.

Update, 31 Aug 2014: HTML5 rocks! You can do this easily now, using CSS flexbox layout.

Programming
Web
CSS