Signup/Sign In

How to center a table with CSS?

The tables are widely used found on the webpage. The tables are left-aligned by default. We can align the table to the center using CSS. In this tutorial, we will be learning about the CSS properties used to center align the tables.

Using CSS margin property

The table can be centered using the CSS margin property. The auto value is used with margin property to create equal spacing to right and left of the table.

Example: Center align the table using the CSS margin property

In this example, we used margin:auto to center align the table.

<!DOCTYPE html>
<html lang="en">
<head>
 <title>HTML </title>
 <style>
    table, th, td{
      border: 1px solid black;
    }
	table {
	  margin: auto;
	}
  </style>
</head>
<body>
  <h2 style="text-align: center"> Center the table </h2>
  <table>
    <tr>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3 </td>
      <td>item 4</td>
    </tr>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3</td>
      <td>Item 4</td>
    </tr>    
  </table>
</body>
</html>

Output

Here is the output of the above program.

center the table

Using flexbox property

We can also use the CSS flexbox property to center the table. To do so first change the display property of the body to flex and then use justify-content:center property to the body. We also need to specify height and width.

Example: Center align the table using flexbox property

In the following program, we have used flex property to HTML body to center align the table.

Conclusion

In this tutorial, we have centered the table on the webpage using CSS property. We can easily do so using margin:auto property or flexbox property.



About the author: