Center-align a HTML table

FabricePMW picture FabricePMW · Dec 28, 2012 · Viewed 308.5k times · Source

On a page I'm working on at the moment, I can't seem to be able to center a table with an image in the first row and two columns of text below it (the two columns shouldn't be more than the image's width) Here's the page : http://www.puzzles-et-jeux.com/fr/page/minipuzzles.html I spent a lot of time trying to solve this. I would like to keep it in HTML because I have to rush and also because I have to create 20 pages of the sort with different widths /+ layouts for each image.

Answer

Wesley Porter picture Wesley Porter · Dec 28, 2012

For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.

In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center" attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class or you can put the style inline with the HTML. Here are the two options:

  1. With a class:

    <table class="centerTable"></table>

In your style.css file you would have something like this:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:

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

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.