OneBite.Dev - Coding blog in a bite size

center a table in css

Code snippet for how to center a table in css with sample and detail explanation

In this article, we will delve into the fantastic world of web designing with a focus on how to center a table using Cascading Style Sheets (CSS). Whether you’re a beginner trying to get the hang of CSS or an intermediate frontend developer looking to brush up on your skills, this straightforward tutorial will guide you on every step.

Code snippet to Center a Table in CSS

Begin by utilizing the following code snippet:

.table-center {
    margin-left: auto;
    margin-right: auto;
    display: table;
}

That’s the CSS you need to center a table!

However, to apply this style to your HTML table, assign the class table-center to your table as shown below:

<table class="table-center">
    <!-- Your table content here -->
</table>

Code Explanation for Centering a Table

This section will explain the code snippet defined above and help you understand what each line of the CSS rule does. This will further equip you with enough knowledge to fully grasp how CSS controls the layout and styling of an element.

In the CSS rule:

  • .table-center: This is the class selector that we’ll attach to the table in our HTML. It allows us to apply specific styles to that table.

  • margin-left: auto; and margin-right: auto;: These two properties allow the browser to automatically calculate and distribute the left and right margins equally. This, in turn, centers the selected element (our table) horizontally within its parent element.

  • display: table;: This property is used to specify that an element should be treated as a table. Here, it’s important when you want different elements (not just <table>) to behave like a table for layout purposes.

By combining these properties and values into the .table-center class and assigning it to our HTML table, we instruct the browser to center this table element within its parent. If everything was done correctly, your table should now be centered on the screen!

That’s it! You’ve successfully centered a table in CSS. This can be quite handy when arranging elements in your webpage for a balanced and visually pleasing layout. Keep practicing this together with other CSS techniques to improve your web design skills.

css