Forum Moderators: not2easy

Message Too Old, No Replies

Center table with CSS

Center table with CSS

         

Adam5000

9:00 pm on Feb 9, 2008 (gmt 0)

10+ Year Member



I've got a paragraph inside a table and I've set the table width to 300px. And I'm trying to center the table horizontally on the page and vertically align it at the top of the page using CSS. Below is the HTML code.

<table width="300px" align="center"
<tr>
<td>
<p>Text here</p>
</td>
</tr>
</table>

This works in HTML, and I'd like to do the same thing with CSS. My best attempt is below.

<table style="width=300px; align: center;">
<tr>
<td>
<p>Text here</p>
</td>
</tr>
</table>

But instead of
<table style="width=300px; align: center;">
centering the table on the page, it centers the text inside the table.

Help!

swa66

10:52 pm on Feb 9, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Standard CSS to center something is to set left and right margins to "auto". "align:center" is not valid CSS AFAIK.

There's a catch with the auto margins: IE6 is notoriously bad at doing what it should do, so you might need to set -for IE's sake- text-align: center on the parent element.

Adam5000

12:51 am on Feb 10, 2008 (gmt 0)

10+ Year Member



That worked great. The <body style="margin-left: auto; margin-right: auto;"> replaces the align center code (which the validator threw a fit about).

But I'm still having trouble with the scroll bar on the side. For some reason, when I resize the window and the scroll bar gets close to the right margin, the page stops centering. And the bottom scroll bar doesn't appear until the side scroll bar is against the right margin. What I'd like is to set the table width to 300px and have the table centered on the page for all window widths more than that.

swa66

3:24 am on Feb 10, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Take care with width and auto margins on the <body> tag: IE6 doesn't like it.

Scrollbars: never seen that behavior myself. Perhaps give us a bit more info like what browser, doctype etc. you're using.