Connect with us

CSS

CSS: How to Align a Table to the Center

Spread the love

Centering a table on a webpage is one of the most common layout tasks in HTML and CSS. Whether you’re creating a data-driven dashboard or a simple pricing table, making sure your table is aligned properly improves visual structure and user experience.

In this post, you’ll learn several methods to horizontally center an HTML <table> using CSS, with clean and practical examples.


โœ… Method 1: Using margin: auto

The most straightforward and modern method is to use CSS margin: auto on a block-level element with a specified width.

HTML

<table class="center-table">
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Widget</td>
    <td>$19.99</td>
  </tr>
</table>

CSS

.center-table {
  margin-left: auto;
  margin-right: auto;
  border-collapse: collapse;
  width: 50%;
}

This method works perfectly for centering tables horizontally. You can also use margin: 0 auto; as a shorthand.


โœ… Method 2: Using Flexbox (Modern Approach)

If your table is inside a container, you can use Flexbox to center it.

HTML

<div class="table-container">
  <table>
    <!-- table content -->
  </table>
</div>

CSS

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

This gives you more control and works well with responsive layouts.


โœ… Method 3: Using text-align: center (Less Preferred)

Another older approach involves using text-align: center on the parent container. While it works, it’s not the most robust or modern method.

.container {
  text-align: center;
}
.container table {
  display: inline-table;
}

โŒ What Not to Do

Avoid using deprecated attributes like align="center" in your HTML. For example:

<!-- Deprecated -->
<table align="center">

This may still work in some browsers but is not considered best practice in modern HTML5.


๐Ÿงช Quick Comparison

MethodModernResponsive-FriendlyRecommended
margin: autoโœ…โœ…โœ…
Flexboxโœ…โœ…โœ…โœ…โœ…โœ…
text-align: centerโŒโŒNot Ideal
align="center"โŒ DeprecatedโŒโŒ

โœ… Final Thoughts

Centering a table with CSS is simple and clean with modern techniques like margin: auto or Flexbox. These methods provide better control over layout and responsiveness without relying on outdated HTML attributes.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *