Your IP: 216.73.216.131 [Columbus]
Read News/Blog Back to News/Blog List

How To Center A Whole Table With CSS

Someone asked in one of our developer groups on how to center an HTML table using CSS. Centering a table to its container is basically just like centering any other element in HTML using CSS. In this guide, I will share two easy ways to center the table.

For the purpose of this tutorial, this is the index.html file that I use:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Center table</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <hr>
  <div class="tbl-container">
    <table border="1">
      <thead>
        <tr>
          <th> </th>
          <th>Listening</th>
          <th>Reading</th>
          <th>Speaking</th>
          <th>Writing</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>English</td>
          <td>C2</td>
          <td>C1</td>
          <td>C1</td>
          <td>C2</td>
        </tr>
        <tr>
          <td>Spanish</td>
          <td>A2</td>
          <td>A1</td>
          <td>A1</td>
          <td>A1</td>
        </tr>
      </tbody>
    </table>
  </div>
  <hr>
</body>
</html>

Center using margins

The first method is by using margins. To center any block element in HTML (table is a block element), we can set the left and right margins to auto. When the left and right margins are both set to auto, the browser will automatically distribute the margins to the left and right, thus putting the element right in the middle of its container.

In my style.css file:

table {
  margin: 0px auto;
}

Center using flex

The second method is by using flexbox. Flexbox is, in most cases, the better way to center elements inside a container. By using flexbox, the styling is applied to its container, and not the elements itself as in the case of the first method above.

Using flexbox, in my style.css file:

.tbl-container {
  display: flex;
  justify-content: center;
}

Both these methods will work fine to ensure that the HTML will be centered within its container. If you have any further questions regarding the matter, just send me an email at naim@amz.com.my, or you can also share with me any better methods that you know.

How To Center A Whole Table With CSS
AuthorNaim Zulkipli
Date26 June 2023
Share This Post:
Chat with Us! Chat with AMZ IT Solutions

Contact AMZ IT Solutions

Message / Enquiry:
Close This

Become an Affiliate of AMZ IT Solutions

By submitting this form, you agree to have your information stored and managed by AMZ IT Solutions, and to be contacted by AMZ IT Solutions for administration, marketing, and training purposes.

Close This
Logo of AMZ IT Solutions

Your screen is too small to view our full website.

For any enquiries, please contact us:

+6011-2088 4110 admin@amz.com.my