Home >Web Front-end >CSS Tutorial >Why Don't Margins Work on divs with `display: table-cell;`?

Why Don't Margins Work on divs with `display: table-cell;`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 09:16:10407browse

Why Don't Margins Work on divs with `display: table-cell;`?

Why Can't divs with "display: table-cell;" Apply Margins?

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.

Cause: Incompatibility with "display: table-cell;"

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.

Solution: Border-Spacing Property

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

Margin Variation on Horizontal and Vertical Axes

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn