How (and why) to use display: table-cell (CSS)

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the “How”:

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you’d have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you’d use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

#table {
    display: table;
    padding: 5px;
}
.tr {
    display: table-row;
    padding: 5px;
}
.td {
    display: table-cell;
    padding: 5px;
    width: 150px;
    border: #000000 solid 1px;
    margin: 5px;
}
<div id="table">
    <div class="tr">
        <div class="td">Row 1,
            <br />Column 1</div>
        <div class="td">Row 1, Column 2</div>
        <div class="td" style="background:#888888;"></div>
    </div>
    <div class="tr">
        <div class="td">Row 2,
            <br />Column 1</div>
        <div class="td">Row 2, Column 2</div>
        <div class="td" style="background:#888888;"></div>
    </div>
</div>

 Run code snippetExpand snippet

It’s worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

Leave a Comment