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 [email protected], or you can also share with me any better methods that you know.