Table alignment

In the old days it was easy to align a table in the center of the page. You just use

<table align="center">

and viola, your table is centered!

The code is also very easy to understand, any one can understand what you are doing!

The code says it all, you have a table and you want to align it in the center! Easy right?

The bad news is that the align tag is now deprecated so you have to use css instead.

To center a table you need to use the following code:

<table style="margin: 0 auto;">

This is NOT easy to understand like the old code. Can someone please explain to me how the “margin: 0 auto;” works?
The first thing that I thought was, what the hell does a 0 and an auto have to do with centering a table?

When you set a margin, you can give four values - top, right, bottom and left - which can all be different.
If the margin on all four sides is the same then you just give a single value.
So what about two values? That’s for when the top and bottom are the sams, and the left and right are the same. So you give top/bottom then left/right.

A top/bottom margin of 0 is self explanatory. A left/right margin of auto means that it will divide the space that is left evenly between the left and right - ie, it will be centred. No, it may not be as immediately obvious but it is a lot more powerful than being limited to align=left/center/right.

Thanks for the explanation.

So if I’m centering text then I should use “text-align: center”, but when centering non-text (like tables, divs, submit button, etc.) then I should use “margin: 0 auto;”? Is this correct?

For margin: 0 auto to center an element, it must be either a block level element (like a div, table etc.) or an inline element set to display: block. Left and right auto margins will center block level elements like divs, tables etc. that have a width declared (as, without a set width they will tend to be 100% wide—unless set to display: table or similar).

Elements that are inline or inline-block (such as text, images, spans etc.) can only be centered with text-align: center set on their block level parent element.