Centering HTML table by using Flexbox Property
CSS flexbox Property provides a flexible way to align and distribute space among items within a container. It offers properties like display: flex for creating a flex container and justify-content, and flex to control item positioning, alignment, and sizing. The align-items property can make the table data aligned to the center.
Syntax:
.table-container {
display: flex;
justify-content: center;
}
Example:
HTML
<!DOCTYPE html> < html > < head > < style > .table-container { display: flex; justify-content: center; } table, th, td { border: 1px solid black; } </ style > </ head > < body > < h2 >Centering an HTML Table with CSS Property</ h2 > < h3 >Using "display: flex" & "justify-content: center;" Property</ h3 > < div class = "table-container" > < 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 > </ div > </ body > </ html > |
Output:
Explanation: CSS flwxbox property is an advance topic of CSS, it helps us to render any HTML element in formatted way. CSS display: flex property provides a flexible way to align and distribute space among items within a container.
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 > |
Contact Us