View Single Post
  #5 (permalink)  
Old 04-30-09, 04:57 AM
harish harish is offline
Newbie Coder
 
Join Date: Apr 2009
Posts: 52
Thanks: 0
Thanked 0 Times in 0 Posts
Method 1
To center a table, you need to set the margins, like this:

Code:
  table.center {margin-left:auto; margin-right:auto;}
And then do this:
Code:
  <table class="center">
    ...
  </table>
At this point, Mozilla and Opera will center your table. Internet Explorer 5.5 and up, however, needs you to add this to your CSS as well:
Code:
  body {text-align:center;}
Method 2

If you want your table to be a certain percentage width, you can do this:
Code:
  table#table1 {width:70%; margin-left:15%; margin-right:15%;}
And then in your HTML/XHTML, you would do this:
Code:
  <table id="table1">
    ...
  </table>
Note that I was using an id to describe the table. You can only use an id once on a page. If you had many tables on a page that you wanted to be the same width and centered, you would do this in your CSS:
Code:
  table.center {width:70%; margin-left:15%; margin-right:15%;}
And this in your HTML:
Code:
  <table class="center">
    ...
  </table>

  <table class="center">
    ...
  </table>
Method 3

If you want your table to be of fixed width, define your CSS like this:
Code:
  div.container {width:98%; margin:1%;}
  table#table1 {text-align:center; margin-left:auto; margin-right:auto; width:100px;}
  tr,td {text-align:left;}
Set "width:100px" to whatever width you need.

"text-align: center" is there for Internet Explorer, which won't work without it. Unfortunately, "text-align: center" will center all the text inside your table cells, but we counter that by setting "tr" and "td" to align left.

In your HTML, you would then do this:
Code:
  <div class="container">
    <table id="table1">
      ...
    </table>
  </div>
Reply With Quote