Reading time: 2 minutes
The CSS style to center a table differs depending on whether you want the table to be centered horizontally or vertically.
To center a table horizontally, you need to set the margin-left and margin-right properties to auto .
It’s recommended that you create a class that applies the CSS style so that it won’t affect all of your tables. Here is an example of how to do this:
Add that class to your table as follows:
Alternatively, you can also define a single margin property and set the value to 0 auto like this:
The margins on top and bottom will be set to 0 while the left and right margins will be set to auto .Center table vertically
To center the table vertically on the browser, you need to make use of CSS Flexbox layout and create a container element for the table (like a ).
The container element must also have a fixed height property for the vertical centering to work.
First, you need to write the CSS for the container as follows:
The height property of the container must be higher than the table, or the centering won’t work.
Add that CSS to the element that contains your table as shown below:
You will see the table rendered in the center vertically like this:
If you want the table to be centered vertically and horizontally, add justify-content: center; property to the flex-center class:
With that property, the table will be centered horizontally and vertically inside the as follows:
To conclude, centering a table with CSS can be done vertically or horizontally, or both.
You can use the CSS styles shown in this tutorial to help you achieve the desired output.
Another element that you might want to center a lot is a button, so I also created a guide on centering button elements with CSS.
You might want to check it out.
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Type the keyword below and hit enter
Click to see all tutorials tagged with: