Center an image with CSS

February 19th, 2007. Tagged: CSS

Here's one solution to centering an image both horizontally and vertically, when you know the height of the container. Tested in FF, IE6, IE7

The markup:

<div class="container">
    <img src="pearbook.png" />
</div>

Styles for normal browsers:

.container {
    height: 200px;
    width: 300px;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    border: 1px solid red;
}
.contain img {
    vertical-align: middle;
}

and IE exception:

<!--[if IE]>
<style type="text/css">
    .container {
        font-size: 181px;
    }
</style>
<![endif]-->

You might wonder where 181px come from? Well, this is the height of the div that contains the image, multiplied by 0.905. Crazy, eh? But it works! And why 0.905? No idea, I saw that in a blog posting which I have hard time locating now in order to give proper credit. A guy was experimenting and he came up with this coeficient.

Here's a test page.

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov