What is display table in CSS: Explanation and Example
display: table property in CSS makes an element behave like an HTML <table> element, controlling layout in a table-like way. It helps arrange child elements as rows and cells without using actual table tags.How It Works
Think of display: table as turning a regular box into a table container. Just like a table in real life holds rows and cells, this CSS property makes the element act like a table, so its children can be arranged like rows and cells.
When you set an element to display: table, its direct children can be set to display: table-row and display: table-cell. This creates a grid-like layout without using actual HTML table tags. It’s like building a table structure with CSS boxes.
This method is useful when you want the alignment and sizing features of tables but want to keep your HTML semantic and flexible.
Example
This example shows a container styled as a table with two rows and two cells each. The cells align neatly like a real table.
<style>
.container {
display: table;
border: 2px solid #333;
width: 300px;
margin: 20px;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
border: 1px solid #666;
padding: 10px;
text-align: center;
}
</style>
<div class="container">
<div class="row">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
</div>
<div class="row">
<div class="cell">Cell 3</div>
<div class="cell">Cell 4</div>
</div>
</div>When to Use
Use display: table when you want to create a table-like layout but prefer to keep your HTML semantic and avoid actual <table> tags. It is helpful for aligning items in rows and columns with consistent sizing.
For example, you might use it for custom grid layouts, aligning buttons or labels next to inputs, or creating complex forms where table structure helps with alignment but semantic HTML is important.
It is less common now with CSS Grid and Flexbox available, but it can still be useful for simple table-like layouts without extra markup.
Key Points
display: tablemakes an element behave like a table container.- Child elements can be
table-rowandtable-cellfor row and cell behavior. - Helps align content in rows and columns without HTML tables.
- Useful for layout alignment but less common with modern CSS layout tools.
Key Takeaways
display: table creates a table-like layout using CSS without HTML tables.table-row and table-cell on children to build rows and cells.