A Simple Way to Center a Table Using CSS

One line of code is all you need to center a table

Laptop with CSS word on screen

hardik pethani / Getty Images 

Cascading Style Sheets set the visual style of web pages written in HTML and XHTML. In the past, designers used the center tag or the align="center" attribute, but these approaches aren't valid for modern table elements. Now, the optimal method of aligning a table relies on a single line of CSS.

Use CSS to Center a Table

To center a table, specify the margins of a table class in CSS:

table.center {

And then add the relevant class identifier within the HTML:

<table class="center">

Fixing a Percentage Width

To set a specific width for your table, call out the percentage in a width attribute in the CSS, and then balance the placement of the table through percentage adjustments of the left and right margin, as follows:

 table.center {

The total of the left, right, and width markers must equal 100 percent.