Centering a fixed-width table with CSS - Mozilla and IE.

Technical Q&A involving operating systems, networking, software, and hardware issues.

Moderator: jasonb

Post Reply
User avatar
jasonb
Site Administrator
Posts: 105
Joined: Tue Apr 22, 2003 1:54 pm
Location: Toronto, Canada
Contact:

Centering a fixed-width table with CSS - Mozilla and IE.

Post by jasonb »

This one is a real pain. While Mozilla properly handles the "margin-[left/right]: auto" directive, IE ignores it completely. Similarly, using "text-align: center" works in IE (although with some additional complications) but not in Mozilla.

Previously, I'd been using tables with emptly <td></td> tags before and after the "table" (really just a column) I'd wanted to center. However, while this worked for the most part it was not only a "hack" but also had some unexpected formatting issues in older versions of IE. I was grateful to recently discover a better method.

The solution is to simply use both, as per the following:

Code: Select all

<div style="text-align: center">
<div style="margin-left: auto; margin-right: auto; width: 100px; text-align: left">
<table width="100px">
<tr>
<td>
Some text.
</td>
</tr>
</table>
</div>
</div>
Some notes on the above:
  • The order of the <div> statements is important. If you don't use the IE version first, it won't work.
  • Notice the use of "text-align: left" in the declaration of the 2nd <div>. This "fixes" the center alignment of text caused by the IE <div> statement, while still preserving the center alignment of the block as a whole.
  • You have to specify a width for the 2nd <div>. If you don't, it doesn't get centered but stays left aligned.
  • Using "100px" is just an example, it can be changed to any other value or unit of measurement you want.
  • This method need not apply to just tables. You can use whatever you want as part of the <div> block.
  • Obviously, this only effects horizontal alignment. Vertical alignment is something else. I haven't "solved" that one yet since I haven't had to use it personally. (Once again, IE ignores the vertical alignement tag that's a CSS standard and which Mozilla follows.)
Post Reply