Cover Image for How to center a table in CSS
128 views

How to center a table in CSS

To center a table in CSS, you can use the margin property along with auto value for both the left and right margins. This technique works well when you want to center the entire table within its parent container.

Here’s an example of how to center a table:

HTML:

<div class="table-container">
  <table>
    <!-- Table content goes here -->
  </table>
</div>

CSS:

.table-container {
  display: flex;
  justify-content: center;
}

In this example, we have a <div> element with the class “table-container” that wraps the <table> element. We use CSS Flexbox to center the table horizontally within the .table-container div.

The display: flex; property is applied to the .table-container div, which turns it into a flex container.

The justify-content: center; property is then used to horizontally center the table inside the flex container. The center value for justify-content means that the table will be centered along the main axis (horizontal axis in this case) of the flex container.

This method centers the entire table, including its content and any other elements within the table, such as rows, cells, or other HTML elements.

If you want to center just the table itself (excluding its content), you can use the margin property on the table directly:

HTML:

<table class="centered-table">
  <!-- Table content goes here -->
</table>

CSS:

.centered-table {
  margin: 0 auto;
}

In this case, the margin: 0 auto; will automatically center the table within its parent container by setting equal left and right margins. This technique works because setting the left and right margins to auto allows the browser to automatically calculate and distribute the remaining space equally on both sides, effectively centering the table horizontally.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS