Saturday, March 31, 2012

Problems centering a div on a page in IE

When centering a div I usually use margin: 0 auto; but recently I found that sometimes this does not work in IE9. Instead, IE9 ignores the auto margins and puts everything on the left. Here's how to solve this problem.

Problem: IE9 does not center divs when using auto margins.

Impact: The layout looks messed up and can be a little hard to read if everything is out of line.

Solution:
When setting auto margins don't work for centering a div, use text-align instead. In your CSS, set the text-align for the parent to center and set the child div's (the centered div) text-align property to left.

In other words, if you want to center a div of the CSS class "mydiv" within the body of a page, put the following in your CSS:

body {
   text-align: center; /* so all content in the body is centered */
}

.mydiv {
   text-align: left; /* so the content isn't centered as well */
}

Your div should now be centered on the page.

0 comments:

Post a Comment