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
Table Container: Setting an element's
display
property totable
makes it act like a<table>
element. You can then usedisplay: table-row;
anddisplay: table-cell;
for its children to mimic<tr>
and<td>
elements, respectively.Row and Cell Behavior: Elements set to
display: table-row;
act like table rows (<tr>
) and will contain elements set todisplay: table-cell;
, which act like table cells (<td>
).Automatic Sizing: By default, the 'table' will adjust its size to fit its content, similar to how HTML tables work.
No Column and Row Span: Unlike HTML tables, you cannot span rows and columns directly. However, you can mimic this behavior with nested 'tables'.
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
Semantic Use: Use
display: table;
only for layout purposes, not for displaying actual tabular data. For tabular data, use HTML tables.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.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.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.