Juneikerc.com

How to Center an HTML Table with CSS

Featured image for the post: How to Center an HTML Table with CSS

HTML tables allow us to present a lot of information in an organized way, so it's important to know how to work with them. Below, we present 3 ways to center an HTML table using CSS.

Centering an HTML Table with the 'margin: auto;' property

This is probably the most commonly used method to center an HTML table. Simply add 'auto' values to the margin-left and margin-right properties.

This is not the method I recommend, below you have two ways to do it with which you can have complete control over the position of the table within a container.

html
<table class="table">
<tr>
<td><b>Name</b></td>
<td><b>Last Name</b></td>
<td><b>Date</b></td>
</tr>
<tr>
<td>Carlos</td>
<td>Castillo</td>
<td>02/11/1998</td>
</tr>
<tr>
<td>Pedro</td>
<td>Martínez</td>
<td>01/21/1990</td>
</tr>
</table>
css
.table {
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
Please do not use inline styles.

Do not write styles within the HTML tag; assign a class to the table and apply the necessary properties for centering in a CSS stylesheet. Avoid doing this ⬇️

html
<table
style="border:1px solid black;margin-left:auto;margin-right:auto;"
></table>

Centering an HTML Table with Grid Display

Another option, and the one I personally recommend, is to use a layout property like grid or flexbox by wrapping the table you need in a container div.

That's what divs are for, to help us structure our content.

Important note:

We should also avoid overusing divs as they will make our HTML code messy and difficult to maintain in the future.

html
<div class="table-wrapper" >
<table class="table" >
<tr>
<td><b>Name</b></td>
<td><b>Last Name</b></td>
<td><b>Date</b></td>
</tr>
<tr>
<td>Carlos</td>
<td>Castillo</td>
<td >02/11/1998</td>
</tr>
<td>Pedro</td>
<td>Martínez</td>
<td >01/21/1990</td>
</tr>
</table>
</div>
css
.table-wrapper {
display: grid;
place-content: center;
}
.table {
border: 1px solid black;
}

Centering an HTML Table with Flex Display

html
<div class="table-wrapper" >
<table class="table" >
<tr>
<td><b>Name</b></td>
<td><b>Last Name</b></td>
<td><b>Date</b></td>
</tr>
<tr>
<td>Carlos</td>
<td>Castillo</td>
<td >02/11/1998</td>
</tr>
<td>Pedro</td>
<td>Martínez</td>
<td >01/21/1990</td>
</tr>
</table>
</div>
css
.table-wrapper {
display: flex;
justify-content: center;
}
.table {
border: 1px solid black;
}
Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me