css html programming Quick Tips

Centering an HTML table with CSS

With the table attribute align=”center” it is necessary to define table positions using CSS. Here is how.

As you may have noticed, the table align=”center” attribute has been deprecated. So how is one supposed to center a table in an HTML page? The answer is with CSS. However, this is not as straight forward as you would think. Basically we now need to inform the browser to put the same amount of empty space on either side of our tables. Here is how to do it:

The inline method

<table style="margin:auto;">

Or if you are using an attached stylesheet you can do it with either classes or the ID method, or by further defining the table tag.

Here are some lines from a CSS stylesheet showing all three methods (you only need to use one of them, so choose what works best for you)

/* this will define the table tag */
table { margin:auto }
/* this will define an ID to assign the style to */
# table_align { margin:auto }
/* and lastly this is a css class that can be used */
.table_align { margin:auto }

Now, here is the html to make use of these three methods

<table class="table_align" id="table_align">

NOTE: Using “margin:auto” is a bit of overkill since it is basically affecting the margin on all 4 sides of the table in some way. You could center the table more precise by using the margin-left:auto and margin-right:auto and setting two properties in CSS. However, I usually find that the regular margin:auto generally does the job when the top and bottom are not a concern.

Unfortunately IE (Internet Explorer) once again is different and chooses not to recognize any of the methods above. So you will be forced to do one of two things.

  1. Add the margin:auto style to your “body” tag OR
  2. Resort to still using the align=”center” attribute for your tables to satisfy IE


<body style="margin:auto">
<table align="center">

I do not like the previous two examples, but sometimes you gotta do what it takes to reach your entire audience.

By Adam

Speaker, author, consultant, OSS contributor, SoFloPHP UG and SunshinePHP Conf organizer, RunGeekRadio Host, Long distance runner and ultra marathoner.