Explain Codes LogoExplain Codes Logo

Why is a div with "display: table-cell;" not affected by margin?

html
responsive-design
css
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 30, 2024
TLDR

A display: table-cell; element ignores margins since it emulates an HTML <td> element, which takes padding instead. For outer spacing, surround it with a <div> and stipulate margins to this outer <div>.

<div style="margin: 10px;"> <div style="display: table-cell; padding: 10px;"> Spaced out cell. </div> </div>

Wrap your cell to define margin. To define space inside a cell, use padding. table-cell doesn't allow direct margins.

Explanation: the behavior of "display: table-cell"

Using the parent element for spacing

The display: table-cell; turns the div into a table cell, similar to an HTML <td>. It doesn't accept margins because of its nature to tightly pack content. To space out display: table-cell; elements, use border-spacing on a parent element with display: table;.

.table { display: table; border-spacing: 10px; /* the secret sauce for div table spacing */ }

Create a <div> for structure:

<div class="table"> <div class="cell"> Have some breathing room, "table-cell"! </div> </div>

Creating spacing within the cell

In the tiny universe of a display: table-cell; element, padding plays the role of space-maker.

.cell { display: table-cell; padding: 10px; /* creates a space bubble inside the table-cell */ border: 1px solid black; /* drawing the line */ }

Using transparent borders for a gap

The alternate technique employs transparent borders on the table cells as a workaround, though remember that they cannot be expressed in percentages.

.cell { display: table-cell; border: 10px solid transparent; /* Invisible borders? Why not! */ }

Different spacing for horizontal and vertical axes

Now, if you're planning to use separate horizontal and vertical spacing, border-spacing accepts two distinct values:

.table { display: table; border-collapse: separate; border-spacing: 5px 10px; /* horizontal and vertical spacing. Best of both worlds! */ }

Simulating margins in table-cells

So, you crave a margin-like aura? One way is to place an internal <div> or <span> with a certain width to feign an external spacing:

<div class="cell"> <span style="width:10px;">Were not faking margins...Just Optical illusion!</span> <div>

Handling multiple cells in a single row

Apply .row {display: table-row;} to sort multiple cells into a neat row:

<div class="table"> <div class="row"> <div class="cell">Cell 1: Hey, friend!</div> <div class="cell">Cell 2: Hi, mate! Nice row we got here, huh?</div> </div> </div>