Home > Web Front-end > CSS Tutorial > Why Doesn't Margin Work on `display: table-cell` Elements?

Why Doesn't Margin Work on `display: table-cell` Elements?

Susan Sarandon
Release: 2024-12-13 06:32:14
Original
762 people have browsed it

Why Doesn't Margin Work on `display: table-cell` Elements?

Element Insensitive to Margin

Problem

Adjacent divs formatted with display: table-cell; remain unaffected by the margin property, even when set to a value of 5px.

Explanation

According to MDN documentation, the margin property does not apply to elements with table display types except for table-caption, table, and inline-table. Consequently, it cannot affect elements with display:table-cell.

Solution

To achieve spacing between these elements, employ the border-spacing property. However, this requires applying display:table and border-collapse:separate to the parent element.

For instance:

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

By using the border-spacing property and adjusting the border-collapse and display settings, you can effectively create margins between div elements styled as display: table-cell;.

Advanced Functionality

As noted by Diego Quirós, the border-spacing property allows you to define different margin values for horizontal and vertical axes. For example:

.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 `display: 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