Center align a container in IE

Today i faced a problem while trying to center align my main div in IE6.

The Problem

#main
{
    width:960px;
    margin:0 auto;
}

This made my div to align itself in the center in firefox and Internet Explorer 7 but, it failed to do the trick for IE6.


After some googling i found following solution on Webcredible.co.uk website. I added my “simple css hack” to make sure it was available only in Internet Explorer.

The Solution

body
{
     _text-align:center;
}
#main
{
     width:960px;
     margin:0 auto;
     _text-align:left;

}

That’s it, we are done this will center align the container in the center of the browser window

Comments

9 responses to “Center align a container in IE”

  1. Donald Organ Avatar

    i dont know setting the following properties works for me

    margin-left:auto;
    margin-right:auto;

    That always seems to do the trick in IE and firefox.

  2. Piers Johnson Avatar

    You don’t need to use that hack, if you use the strict DOCTYPE margin: 0 auto will work in IE6 as it would in all other browsers.

  3. Fawaz Avatar

    Dude your hack worked like a magic ….. Thanks man ….

  4. dz Avatar
    dz

    Amazing hack. I was pulling my hair out over this problem that the strict doctype would not solve as the padding is strange for IE6 for strange reasons.

    Thank you!

  5. Martin Avatar
    Martin

    It’s an amazing trick! Thanks!

  6. Jake Pucan Avatar
    Jake Pucan

    I agree with Piers Johnson says

  7. itsAsecret Avatar
    itsAsecret

    margin-left:auto;
    margin-right:auto;

    This is the same as

    margin:0 auto ;
    ddduuuuhhh, its the shorthand

  8. Vivekanand Avatar

    Hi All,

    I would like to go with Piers Johnson – since when you make the DOCTYPE to Strict and if it is of HTML 4.0 then margin:0 auto; would work in all browsers.

    1. DOCTYPE – Default – HTML 4.0, margin:0 auto; would not work -> for this you need to add text-align:center;
    2. DOCTYPE – Strict – HTML 4.0, margin:0 auto; would work in all browsers
    3. DOCTYPE – Default – XHTML, margin:0 auto; would work like a charm

    This is what I have discovered, when I was working for a project. Its a good R&D for me – hope this might help others…..

    Cheers!
    Vivek [Founder of http://www.developersnippets.com]

  9. Ragu Avatar
    Ragu

    Thank you very much.