Centering a DIV in IE

In order to center a div layer in Internet Explorer it isn't sufficient just to use <div style="margin: auto width: x>". I.e., though <div style="margin: auto width: 300px;>" would show a layer centered within the webpage in Firefox and Netscape, Internet Explorer would show it aligned to the left side of the page.

The trick is to add text-align: center; to the body selector i.e. you could place the following style information in the head section of your HTML code:

<style type="text/css">
body {text-align: center;} /* for IE */
</style>

Then add margin: auto; to the container selector which you want centered and apply text-align: left; on the container to counter the center align for body. I.e. you could add the following for a div layer:

<div style="padding: 5px; width: 300; border: 3px black solid; margin: auto; text-align: left;">

The text should then appear centered in Internet Explorer, Firefox, and Netscape.

This should be a block of text centered within the page. The div tag used is as follows:

<div style="padding: 5px; width: 250; margin: auto; border: 3px black solid">

When viewed with Firefox, Netscape, or Internet Explorer the div section should now appear centered on the page.

If you have an outer block where you have used text-align: left and then use margin: auto within an inner block, you will find that inner block aligned to the left again. You can overcome that by not having that outer block with text-align: left and instead using <p align="left"> to align the text in paragraphs to the left (see the source code for this page for an example).

The following two example HTML files are exactly the same, except that the "Centered in Firefox" one does not have the following code in the head section, which you can see by looking at the source code for both:

<style type="text/css">
body {text-align: center;}
</style>

Centered in Firefox
Centered in all

Note: Tested in Firefox 3.0, Internet Explorer 7.0, and Netscape 7.2 on a Windows XP system.

References:

Center DIV/Container/Layer IE
flumpCakes - CSS & PHP

left arrowPrevious Page