3 replies [Last post]
jim_keller
Offline
newbie
Last seen: 15 years 49 weeks ago
Joined: 2003-12-05
Posts: 7
Points: 0

I seem to have had success creating a cross-platform method for centering tables.

#centeredTable {

display:table;
width: auto;
margin-top: 5px;
margin-left: auto;
margin-right: auto;
text-align: center;
}

You can view an example here:
http://jim.centerfuse.net/css/tables-centered-example.html

IE ignores display:table and doesn't successfully interpret margin: auto, but text-align: center seems to take care of centering the table in IE.
Tested in Opera 7, IE 6, IE 5.5, Mozilla 1.5.
(I have the top margin in there just to move it away from my header a bit.)
It does require that you set a width on your table, or it will simply fill the entire page, though you could get around that with a container DIV (like this: http://jim.centerfuse.net/css/tables-centered-example-no_table_width.html ).

I thought others might be interested in seeing this, since it seems to be a common problem. I had originally developed a slightly more complicated way of doing what I need to do, but this seems to work just as well.
My main concerns are that future versions of IE will break this code because of added support for display:table and margin:auto, or that the specs for display:table; will change in the future, since it seems to be entirely unsupported in some browsers (namely IE).

-Jim Keller

mcrilly
Offline
newbie
England, Cheshire.
Last seen: 15 years 49 weeks ago
England, Cheshire.
Joined: 2003-12-06
Posts: 5
Points: -1

CSS table centering solution

Hi,

Even though I disagree with using tables for layout, this can be quite useful.

Good work.

Daybreak_0
Offline
Enthusiast
Sydney, Australia
Last seen: 16 years 2 days ago
Sydney, Australia
Timezone: GMT+10
Joined: 2003-11-15
Posts: 389
Points: 0

CSS table centering solution

Jim

You should be able to do away with display: table and just add extra margin to top and bottom

Regards
Day

The only way to learn is to do it yourself

jim_keller
Offline
newbie
Last seen: 15 years 49 weeks ago
Joined: 2003-12-05
Posts: 7
Points: 0

CSS table centering solution

>You should be able to do away with display: table and just add extra margin to top and bottom

In Opera, if I didn't use display:table, the DIV did not automatically resize to encompass whatever table I put inside it. It didn't seem to affect the positioning on the screen, but I would imagine it would've caused issues if I had other DIVs next to or around the one with the table in it.