Centering HTML table by using Margin Auto Property
To center a table, set the margin-left and margin-right to auto or we can use the shorthand property margin with the value of auto. The table cannot be centered if the width is set to 100%). The text-align property can make the table data aligned to the center.
Syntax:
.className {
margin-left: auto;
margin-right: auto;
}
// OR
.className {
margin: auto;
}
Example:
HTML
<!DOCTYPE html> < html > < head > < style > table, th, td { border: 1px solid black; } table.center { margin-left: auto; margin-right: auto; } table.center1 { margin: auto; } </ style > </ head > < body > < h2 >Centering an HTML Table with CSS Property</ h2 > < h3 >Using "margin-right: auto;" & "margin-left: auto;" Property</ h3 > < table class = "center" > < thead > < tr > < th >Column 1</ th > < th >Column 2</ th > < th >Column 3</ th > </ tr > </ thead > < tbody > < tr > < td >1.1</ td > < td >2.1</ td > < td >2.1</ td > </ tr > < tr > < td >1.2</ td > < td >2.2</ td > < td >2.1</ td > </ tr > </ tbody > </ table > < h3 >Using "margin: auto" Property</ h3 > < table class = "center1" > < thead > < tr > < th >Column 1</ th > < th >Column 2</ th > < th >Column 3</ th > </ tr > </ thead > < tbody > < tr > < td >1.1</ td > < td >2.1</ td > < td >2.1</ td > </ tr > < tr > < td >1.2</ td > < td >2.2</ td > < td >2.1</ td > </ tr > </ tbody > </ table > </ body > </ html > |
Output:
Explanation: The margin: left and margin: right property set to auto, and that utilize the remaining spaces and keep the table in the center. Same goes with the margin property.
How to center a table with CSS ?
Sometimes we face problems with centering tables on a web page. With the help of the CSS center element, we can center the table on our web page. Here we have two common approaches.
Table of Content
- Centering HTML table by using Margin Auto Property
- Centering HTML table by using Flexbox Property
Let’s create a table where we perform the above-mentioned approaches to make that table center. We will set a border on the table so it looks good if we make the table center.
HTML
<!DOCTYPE html> < html > < head > < style > table, th, td { border: 1px solid black; } </ style > </ head > < body > < table > < thead > < tr > < th >Column 1</ th > < th >Column 2</ th > < th >Column 3</ th > </ tr > </ thead > < tbody > < tr > < td >1.1</ td > < td >2.1</ td > < td >2.1</ td > </ tr > < tr > < td >1.2</ td > < td >2.2</ td > < td >2.1</ td > </ tr > </ tbody > </ table > </ body > </ html > |