Home >Web Front-end >CSS Tutorial >Why Doesn't Margin Work on CSS Table Cells, and How Can I Add Spacing Instead?

Why Doesn't Margin Work on CSS Table Cells, and How Can I Add Spacing Instead?

DDD
DDDOriginal
2024-12-07 14:25:13727browse

Why Doesn't Margin Work on CSS Table Cells, and How Can I Add Spacing Instead?

Margins on Table Cells

In CSS, when you set an element's display property to table-cell, you're creating a table-like structure. However, table cells are not affected by the margin property. The margin property sets the space outside of the element's borders, but table cells don't have borders by default.

Cause

According to the MDN Documentation, the margin property applies to all elements except elements with table display types other than table-caption, table, and inline-table. Therefore, since table-cell is not one of the exempted table display types, the margin property is not applicable to it.

Solution

To achieve the desired spacing between table cells, use the border-spacing property instead. The border-spacing property sets the space between the borders of adjacent table cells. It should be applied to a parent element with a display:table layout and border-collapse:separate.

<br>HTML:<br><div><pre class="brush:php;toolbar:false"><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;

}

Note that border-spacing accepts two values to set different margins for horizontal and vertical axes, if desired.

The above is the detailed content of Why Doesn't Margin Work on CSS Table Cells, and How Can I Add Spacing Instead?. 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
Previous article:How Can I Properly Align an Image Within an HTML `` Element?Next article:How Can I Properly Align an Image Within an HTML `` Element?

Related articles

See more