Tutorial: Centering a table on a page

by Tim Gallant

Note: if you wish to use absolute positioning ("layers" in Dreamweaver-speak) within your centered content, do not use a table as your centering wrapper. Tables and absolutely-positioned divs do not mix well. (See the off-site article "Ten Layer Laws" for explanation.) Instead of wrapping your content in a table and centering the table, use a div for your wrapper. You may find instructions how to center your div here.

Fixed-width table

This demonstrates how to center a table on a page. A background color was added to the table so you can see where the table is.

Here is the CSS:

#maintable {
margin: auto;
width: 700px;
background-color: #ff3;
}

And in your HTML: <table id=maintable> (etc)

Actually, I have applied one more style rule to our table than what you see above: padding. Whereas margin is outside the "box" (in this case, the table), and refers to the distance between the box and the next item (here, the edge of the page), padding is inside the box. It is used to push the contents away from the edge, so that the table does not look crowded. So add this style rule to the CSS above:

padding: 11px;

One problem. . .

There's a browser that doesn't handle margins properly: Internet Explorer 5, both in the Mac and PC versions.

Fortunately, there is a workaround for this. Pretend your table is text. That's right!

Here's a simple line to add to your body tag in your CSS: text-align: center;

Thus, if you don't have anything else defined in the body of your page (and you *should* define a background colour, at least), your CSS will look like this:

body {
text-align: center;
}

This, however, creates another problem: if you center-align the text in the body tag, many browsers will center the text in your table, as well, and you don't want that. So now you have to add a new style to your table: text-align: left;

Thus, your table code now looks like this:

#maintable {
margin: auto;
width: 700px;
background-color: #ff3;
padding: 11px;
text-align: left;
}

That's it. That's the table you are looking at.

But. . . what if you don't want a certain width preset? In other words, you want the table to shrink or expand according to how large the user sets his or her browser?

For that, let's move on to Part 2.

 

Return to main tutorials page.

Tutorial by Tim Gallant of Pactum Web Services © 2005