Sunday, October 25, 2009

Centering a DIV in Internet Explorer 5 through IE 8

As with many CSS Layouts, the need to center a div is common. The most widely used way to approach this problem is to use the margin attribute in CSS.

The following code is an approach to this problem.

<style>
.container
{
   width:500px;
   height:100px;
   background-color:green;
}
.box
{
   width:100px;
   height:100px;
   background-color:red;
   margin:auto 0px;
}
</style>
<div class="container">
   <div class="box">
   </div>
</div>

Notice the "margin: 0px auto" on the .box class. This tells the browser that you want the top and bottom margins of the .box class to be 0px and the left and right to automatically be set to center the box.

Well this wouldn't be an issue, but in IE 5, 6, 7, and 8 it looks like this:


In every other browser the result is as expected:


The fix for this is simple, just put a text-align attribute on the "container" and set its value to "center".

<style>
.container
{
   width:500px;
   height:100px;
   background-color:green;
   text-align:center;
}
.box
{
   width:100px;
   height:100px;
   background-color:red;
   margin:auto 0px;
}
</style>
<div class="container">
   <div class="box">
   </div>
</div>

And now it will look the same in all browsers:


NOTE: There are multiple ways to do this, but this has been the easiest one I've encountered.

No comments:

Post a Comment