In HTML, divs are adjacent elements that can be arranged using CSS layout settings like "display". When assigning "display: table-cell;", these divs behave like cells within a table and inherit specific properties. One such property is the ineffectiveness of the margin property.
According to MDN documentation, margin is not applicable to elements with table display types other than "table-caption", "table", and "inline-table". "display: table-cell;" falls under this exception, rendering it incompatible with margin.
Instead of using margin, consider applying border-spacing to achieve spacing between divs. However, this property must be applied to a parent element with a "display: table" layout and "border-collapse: separate".
Example:
HTML:
<div class="table"> <div class="row"> <div class="cell">123</div> <div class="cell">456</div> <div class="cell">879</div> </div> </div>
CSS:
.table { display: table; border-collapse: separate; border-spacing: 5px; } .row { display: table-row; } .cell { display: table-cell; padding: 5px; border: 1px solid black; }
See jsFiddle Demo
As mentioned by Diego Quieros, border-spacing supports two values to create different margins for the horizontal and vertical axes.
Example:
.table { /*...*/ border-spacing: 3px 5px; /* 3px horizontally, 5px vertically */ }
The above is the detailed content of Why Don't Margins Work on divs with `display: table-cell;`?. For more information, please follow other related articles on the PHP Chinese website!