Centering a Div in IE9 Using margin:auto

Almost 2 years ago I after Internet Exploder 8 was released I wrote a post about how to get divs to center properly when using margin:auto in your CSS. Now with the release of IE9 - yet another piece of shit MS browser - I’ve encountered similar issues with getting it to obey centering styles.

For IE8 there were 3 different methods that could be used to make it work;

  • Set Width:100% on the containing element
  • Set Text-Align:Center on the containing element
  • Use Transitional Doc Type

With IE9 the use of the Transitional Doc Type is now obsolete, at least for me as I’m building in HTML5 now. Maybe it still works if you use the Transitional, I don’t know. Nor do I care, so I wont bother testing it. If someone tries it please leave a note in the comments as to whether or not that works.

In my testing the text-align center trick is not working for IE9 - so that’s off the table too. Good, this was a dumb hack anyways. Having to set a broader element with centered text alignment then every other element inside it would need to be reset to left alignment - makes for bloated CSS files.

Solution : Set Width:100% on the Containing Element

So the fix is to set your containing element, the one the centered element is to be centered within, to have a width of 100%. That will get that pesky div to center in Internet Explorer 9.

For example, if your were building a fixed width centered web page that was to be 1024 pixels wide you could set the body to width:100% then set your wrapper div or what have you to width:1024px and then center it with margin:0 auto. So your CSS might look like this;

body {width:100%}
#wrapper {width:1024px;margin:0 auto}

The one extra rule of width:100% does not add much bloat, though it should not be necessary if the asshats on the Internet Exploder dev team could ever get their act together and build a browser that renders as well as FireFox, Chrome, Safari or Opera.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlinkList
  • Furl
  • Propeller
  • Slashdot
  • StumbleUpon
  • Technorati

3 Comments to “Centering a Div in IE9 Using margin:auto”

How to Center A Div with margin:auto in IE8 | Stever.ca on January 5th, 2012 wrote:

[…] note: Newer post has solutions for centering in IE9 […]

Kirk on July 15th, 2012 wrote:

Thanks alot. This was the perfect solution!
And I share your thoughts about MS and building shit ass browsers!

Jaedis on October 15th, 2012 wrote:

Thank you for clarifying this. IE9 has been/is such a thorn in my side for website development.

Regards,

Jaedis

Leave a Comment