2012年1月30日星期一

Center Tables :: Scott Granneman

Center Tables :: Scott Granneman

Center a table with CSS

The old way to center a table was easy:

       ...   

The "align" attribute has been deprecated, however, in favor of CSS (Cascading Style Sheets), and this is a good thing. However, it's not so obvious how to center a table using CSS.

The obvious way might appear to use the CSS "text-align: center;" somewhere, maybe like one of these:

  

OR

  
...

OR, if you get really desperate,

              ...     

None of these will work. The table itself will be left-aligned, but all the content in the table cells will be centered.

Why? Because "text-align" applies to inline content, not to a block-level element like "table".

Method 1

To center a table, you need to set the margins, like this:

  table.center {     margin-left:auto;      margin-right:auto;   } 

And then do this:

       ...   

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:

  body {text-align:center;} 

没有评论: