Skip to main content

Table Display

The display: table; value in CSS allows you to make an element behave like an HTML <table> element. This is particularly useful for creating grid-like layouts without using the actual table markup, which is semantically incorrect for non-tabular data.

Characteristics

  1. Table Container: Setting an element's display property to table makes it act like a <table> element. You can then use display: table-row; and display: table-cell; for its children to mimic <tr> and <td> elements, respectively.

  2. Row and Cell Behavior: Elements set to display: table-row; act like table rows (<tr>) and will contain elements set to display: table-cell;, which act like table cells (<td>).

  3. Automatic Sizing: By default, the 'table' will adjust its size to fit its content, similar to how HTML tables work.

  4. No Column and Row Span: Unlike HTML tables, you cannot span rows and columns directly. However, you can mimic this behavior with nested 'tables'.

  5. Alignment: Vertical alignment is straightforward in table display, as it mimics the behavior of HTML tables. You can use vertical-align: middle; to easily vertically center content within a 'cell'.

Example-I: Basic Usage

HTML:

<div class="table">
<div class="row">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
</div>
</div>

CSS:

.table {
display: table;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
}

Example-II: Adding Borders

CSS:

.table {
display: table;
border-collapse: collapse;
}
.cell {
display: table-cell;
border: 1px solid black;
}

Example-III: Vertical Alignment

CSS:

.cell {
display: table-cell;
vertical-align: middle;
}

Best Practices

  1. Semantic Use: Use display: table; only for layout purposes, not for displaying actual tabular data. For tabular data, use HTML tables.

  2. Limited Use: With the advent of Flexbox and Grid, the use-cases for display: table; have become limited. Use it only when it's the simplest solution for your specific layout problem.

  3. Browser Support: display: table; has good browser support, including older versions of Internet Explorer, which might make it useful for projects that require legacy browser support.

  4. Avoid Complexity: display: table; is not suitable for complex layouts with rowspans and colspans, nested tables, or dynamically changing layouts.

Understanding display: table; can be useful for certain layout problems, but it's generally less flexible and powerful than modern layout models like Flexbox and Grid.