How to Center a Table in HTML with CSS
If you’re reading this you probanly want to center a table in HTML. You can do this with some CSS. This post shows you how to center a table within its containing element using CSS.
How to center a table with CSS?
Applying CSS styles is the most efficient way to center a table. By setting the left and right margins of the table to auto, you can horizontally center it within its parent element. Additionally, centering the content within the table cells ensures a polished look.
Center the table horizontally
To horizontally center your table, you need to apply specific CSS properties. Here’s how to do it:
table { margin-left: auto; margin-right: auto; }
These lines of CSS instruct the browser to automatically adjust the left and right margins of all <table>
elements, centering them within their parent container.
Example
Consider the following example where we center a table inside a div
element using CSS:
<!DOCTYPE html> <html> <head> <style> .center-table { margin-left: auto; margin-right: auto; } </style> </head> <body> <div> <table class="center-table" border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table> </div> </body> </html>
Centering table content
For the content within the table cells, the text-align
property centers text horizontally, while vertical-align
deals with vertical alignment. Apply these styles like so:
table, th, td { text-align: center; vertical-align: middle; }
This centers the cell content horizontally and aligns it vertically in the middle, enhancing the table's overall appearance.
Invite only
We're building the next generation of data visualization.
Adjusting HTML Table Column Width for Better Design
Robert Cooper
How to Link Multiple CSS Stylesheets in HTML
Robert Cooper
Mastering HTML Table Inline Styling: A Guide
Max Musing
HTML Multiple Style Attributes: A Quick Guide
Max Musing
How to Set HTML Table Width for Responsive Design
Max Musing
Mastering HTML Span Style for Text Customization
Jeremy Sarchet