CSS: Truncate table cells, but fit as much as possible

s4y picture s4y · Mar 9, 2011 · Viewed 100.8k times · Source

Meet Fred. He's a table:

One cell has more content and is wider, the other has less content and is narrower

<table border="1" style="width: 100%;">
    <tr>
        <td>This cells has more content</td>
        <td>Less content here</td>
    </tr>
</table>

Fred's apartment has a bizarre habit of changing size, so he's learned to hide some of his content so as not to push all the other units over and shove Mrs. Whitford's living room off into oblivion:

The cells are now the same size, but only one has its content truncated, and it looks like if the other cell gave if some whitespace, they could both fit.

<table border="1" style="width: 100%; white-space: nowrap; table-layout: fixed;">
    <tr>
        <td style="overflow: hidden; text-overflow: ellipsis">This cells has more content</td>
        <td style="overflow: hidden; text-overflow: ellipsis">Less content here</td>
    </tr>
</table>

This works, but Fred has a nagging feeling that if his right cell (which he's nicknamed Celldito) gave up a little space, his left cell wouldn't be truncated quite as much of the time. Can you save his sanity?


In summary: How can a table's cells overflow evenly, and only when they've all given up all their whitespace?

Answer

ladislav picture ladislav · Oct 13, 2013
<table border="1" style="width: 100%;">
    <colgroup>
        <col width="100%" />
        <col width="0%" />
    </colgroup>
    <tr>
        <td style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.</td>
        <td style="white-space: nowrap;">Less content here.</td>
    </tr>
</table>

http://jsfiddle.net/7CURQ/