Centering a Div in IE8 Using margin:auto
On the count of 3 everybody scream “MICROSOFT SUCKS AND I HATE INTERNET EXPLODER”.
1, 2, 3, go.
I’ve been working on revamping my Sticky Footer code for IE8 compatibility when I ran into a little bug of sorts. If you are using margin:0 auto; to center a div it will cause problems in IE8 if the parent element has either no width already set, or you’ve not set text alignment to center for that parent div, or you are using the wrong doc type declaration.
These are the three fixes I know of;
Width:100%
Set your containing element to width:100%; so then your centered div inside of that one will actually center. Like this;
#container {width:100%;}
#centered {width:400px; margin:0 auto;}
Text-Align:Center
If you apply text-align:center to the containing div IE8 will obey the margin:auto. You then have to un-center your text content inside that centered div with text-align:left. Kind of convoluted, I know. Apparently some web designer have been doing it like that for years as this was an issue with IE5.
#container {text-align:center;}
#centered {width:400px; margin:0 auto;text-align:left;}
Use Transitional Doc Type
If you are using XHTML 1.0 Strict as your doc type, IE8 will not obey the margin:auto method for centering an element, unless you use one of the above hacks. You can also just change your doc type declaration at the top of your page to be XHTML 1.0 Transitional. IE8 will then obey the margin:auto statement.
Here’s a link to doc type declaration syntax.
Oh the joys of cross browser web design.
DoFollow links available for frequent commentors.
5 Comments to “Centering a Div in IE8 Using margin:auto”
Leave a Comment
RSS Feed
The Topics
- Designing and Coding a Mobile Version of your Website
- Updated CSS Sticky Footer for 2010 - Works in IE8
- Centering a Div in IE8 Using margin:auto
- My New Blog about Local SEO
- Local TV Matters? WTF is this Save Local TV Campaign in Canada All About?
- 5 Reasons the Top 7 Bloggers Write Top 10 List Posts and a Few Reasons they Now Annoy Me
- A CSS Sticky Footer that Works in 2009 (Chrome too) (321)
- New iGoogle with Left Nav Bar is the SUCK! (193)
- My Cool Ass CB750 Cafe Racer (66)
- The State of Local Search in Canada (14)
- Geo-Targeting by Country for Organic Search (13)
Recent Stuff












Thanks for this. I thought I was going to loose my mind. Couldn’t find the mistake in my css.
Finally just broke down and searched for it.
thank you..
PS i hate this stupid ms ie8
width:100% helped. Thanks a lot
Nice one!!, thanks for the tips.
This one worked for me even in FF3 that was not working…
“text-align:center”
so at the end, I had to add the following div:
My doctype was wrong! That hint is very precious!
Thanks for the help