CSS table td width - fixed, not flexible

Richard Westington picture Richard Westington · Jul 12, 2011 · Viewed 297.2k times · Source

I have a table and I want to set a fixed width of 30px on the td's. the problem is that when the text in the td is too long, the td is stretched out wider than 30px. Overflow:hidden doesn't work either on the td's, I need some way of hiding the overflowing text and keeping the td width 30px.

<table cellpadding="0" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

Answer

Cᴏʀʏ picture Cᴏʀʏ · Jul 12, 2011

It's not the prettiest CSS, but I got this to work:

table td {
    width: 30px;
    overflow: hidden;
    display: inline-block;
    white-space: nowrap;
}

Examples, with and without ellipses:

body {
    font-size: 12px;
    font-family: Tahoma, Helvetica, sans-serif;
}

table {
    border: 1px solid #555;
    border-width: 0 0 1px 1px;
}
table td {
    border: 1px solid #555;
    border-width: 1px 1px 0 0;
}

/* What you need: */
table td {
    width: 30px;
    overflow: hidden;
    display: inline-block;
    white-space: nowrap;
}

table.with-ellipsis td {   
    text-overflow: ellipsis;
}
<table cellpadding="2" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

<br />

<table class="with-ellipsis" cellpadding="2" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>