Home >Web Front-end >CSS Tutorial >Why Doesn't Margin Work on Table-Cell Elements?

Why Doesn't Margin Work on Table-Cell Elements?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 15:11:14164browse

Why Doesn't Margin Work on Table-Cell Elements?

Why Does Margin Fail on Table-Cell Elements?

Despite assigning margin: 5px to neighboring div elements with display: table-cell, no margin appears. What's the reason?

Understanding the Cause

According to the MDN documentation, the margin property excludes elements with table display types except for table-caption, table, and inline-table. Therefore, margin is ineffective on elements with display: table-cell.

Resolving the Issue

Instead of using margin, consider employing the border-spacing property. This property applies to parent elements with a display: table layout and border-collapse: separate.

Example Code

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;
}

Customizing Margin Values

The border-spacing property can also take two values, allowing for different horizontal and vertical margins.

.table {
  /* ... */
  border-spacing: 3px 5px; /* 3px horizontally, 5px vertically */
}

The above is the detailed content of Why Doesn't Margin Work on Table-Cell Elements?. 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