In this short article, you will learn how to center a table in HTML. You will use the
style attribute to make the table move to the center.
Here’s a sample HTML table that we are going to use for this guide:
<table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>John Wick</td> <td>57</td> </tr> <tr> <td>Tony Stark</td> <td>48</td> </tr> </table>
The simplest way to center the table is to use the
margin: auto. By setting the value of the table’s margin to
auto, it will move the table to the center.
<table style="margin: auto">
What the value
auto does is it tells the browser to automatically adjust the margin size and what the browser will do is it will take up the available space between the left and right sides of the table until it is horizontally centered.
Alternatively, you can also use
margin-left: auto and
margin-right: auto and it will still accomplish the same goal.
<table style="margin-left: auto; margin-right: auto">
What is happening here is the
margin-left: auto will take up the available space on the right side of the table and the
margin-right: auto is doing the same except for the left side. By combining these two, you are effectively making the table be centered.
One thing to keep in mind is the margin auto will not work if you set the table’s width to 100%.
If you also want the content inside the table to be moved to the center, use
text-align and set the value to
center. That way, both your table and its content will be in the middle of the browser’s screen.
<table style="margin: auto; text-align: center">
And that’s it! Now you know how to center a table in HTML.