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
Release: 2024-12-08 09:16:10
Original
357 people have browsed it

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>
Copy after login

CSS:

.table {
  display: table;
  border-collapse: separate;
  border-spacing: 5px;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 5px;
  border: 1px solid black;
}
Copy after login

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 */
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template