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
Release: 2024-12-18 15:11:14
Original
167 people have browsed it

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

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

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!

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