Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why does div display: table-row ignore margin?
The CSS display: table-row property ignores margin because table elements follow the CSS table model, where margins don't apply to internal table components like table-row and table-cell. Instead, spacing is controlled by the border-spacing property or by applying margin to nested elements.
Syntax
.element {
display: table-row; /* Margins will be ignored */
margin: 20px; /* This won't work */
}
Why Table Rows Ignore Margin
The CSS specification states that margin properties don't apply to elements with display: table-row, table-row-group, table-header-group, table-footer-group, table-column, table-column-group, or table-cell (except table-caption and table).
Example: Margin Ignored on Table Cells
<!DOCTYPE html>
<html>
<head>
<style>
.cell1 {
display: table-cell;
margin: 50px; /* This margin will be ignored */
padding: 20px;
background-color: lightgreen;
}
.cell2 {
display: table-cell;
margin: 50px; /* This margin will also be ignored */
padding: 20px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="cell1">Cell 1</div>
<div class="cell2">Cell 2</div>
</body>
</html>
Two adjacent cells appear with no spacing between them despite the margin declarations.
Method 1: Using Border-Spacing
The border-spacing property controls spacing between table cells when applied to a parent element with display: table
<!DOCTYPE html>
<html>
<head>
<style>
.table-container {
display: table;
border-collapse: separate;
border-spacing: 15px;
}
.table-row {
display: table-row;
}
.table-cell {
display: table-cell;
padding: 10px;
background-color: lightcoral;
border: 1px solid #333;
}
</style>
</head>
<body>
<div class="table-container">
<div class="table-row">
<div class="table-cell">Cell A</div>
<div class="table-cell">Cell B</div>
<div class="table-cell">Cell C</div>
</div>
</div>
</body>
</html>
Three table cells with 15px spacing between them, creating visible gaps.
Method 2: Using Margin on Nested Elements
Apply margin to inner elements instead of the table-cell containers
<!DOCTYPE html>
<html>
<head>
<style>
.outer-cell {
display: table-cell;
}
.inner-content {
margin: 15px;
padding: 10px;
background-color: lightyellow;
border: 1px solid orange;
}
</style>
</head>
<body>
<div class="outer-cell">
<div class="inner-content">Content 1</div>
</div>
<div class="outer-cell">
<div class="inner-content">Content 2</div>
</div>
</body>
</html>
Two cells with spacing achieved through margin on the inner div elements.
Conclusion
The display: table-row and table-cell properties ignore margin due to the CSS table model. Use border-spacing on the parent table container or apply margin to nested elements instead to achieve proper spacing between table components.
