How to center a table using CSS?

By IncludeHelp Last updated : November 13, 2023

To center a table using the CSS, set the margin-left and margin-right properties to auto. The margin-left property sets the left-side margin area of the table, and the margin-right property sets the right-side margin area of the table. When we set the auto value to both of the properties, it will center a table on a webpage.

Steps

Step 1: Add HTML

Add HTML of the table i.e., write records into a table.

<table>
  <tbody>
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
    <tr>
      <td>Alex</td>
      <td>21</td>
    </tr>
    <tr>
      <td>Alvin Alexander</td>
      <td>29</td>
    </tr>
    <tr>
      <td>Joseph Stalin</td>
      <td>25</td>
    </tr>
    <tr>
      <td>Martin Luther</td>
      <td>23</td>
    </tr>
  </tbody>
</table>

Step 2: Create a CSS style

Create CSS style (here, the style name is i3-centerTable), set margin-left and margin-right properties to auto.

.i3-centerTable {
  margin-left: auto;
  margin-right: auto;
}

Step 3: Use CSS class

Now, use the CSS class with the <table> tag.

<table class="i3-centerTable">

Example

Consider this example. This example demonstrates how to center a table.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
      body{	
      margin: auto;
      max-width: 1024px;
      }
      table, th, td {
      border: 1px solid black;
      }	
      .i3-centerTable{
      margin-left: auto;
      margin-right: auto;
      }
    </style>
  </head>
  <body>
    <h1>Example to center a table using CSS</h1>
    <p style="text-align:center;"><strong>Student's record</strong></p>
    <table class="i3-centerTable">
      <tbody>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
        <tr>
          <td>Alex</td>
          <td>21</td>
        </tr>
        <tr>
          <td>Alvin Alexander</td>
          <td>29</td>
        </tr>
        <tr>
          <td>Joseph Stalin</td>
          <td>25</td>
        </tr>
        <tr>
          <td>Martin Luther</td>
          <td>23</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

Output

The output of the above example is:

Center a table using CSS

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.