CSS
CSS: How to Align a Table to the Center
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
Method | Modern | Responsive-Friendly | Recommended |
---|---|---|---|
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.