Search code examples
htmlcss

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


I have div elements next to each other with display: table-cell;.

I want to set margin between them, but margin: 5px has no effect. Why?

My code:

<div style="display: table-cell; margin: 5px; background-color: red;">1</div>
<div style="display: table-cell; margin: 5px; background-color: green;">1</div>

Solution

  • Cause

    From the MDN documentation:

    [The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table

    In other words, the margin property is not applicable to display:table-cell elements.

    Solution

    Consider using the border-spacing property instead.

    Note it should be applied to a parent element with a display:table layout and border-collapse:separate.

    For example:

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

    See jsFiddle demo


    Different margin horizontally and vertically

    As mentioned by Diego Quirós, the border-spacing property also accepts two values to set a different margin for the horizontal and vertical axes.

    For example

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