CSS: Constrain a table with long cell contents to page width?

To achieve this, you have to wrap the long text into two divs. The outer one gets position: relative and contains only the inner one. The inner one gets position: absolute, overflow: hidden, and width: 100% (this constrains it to the size of the table cell).

The table-layout algorithm now considers those table cells empty (because absolutely-positioned elements are excluded from layout calculations). Therefore we have to tell it to grow that column regardless. Interestingly, setting width: 100% on the relevant <col> element works, in the sense that it doesn’t actually fill 100% of the width, but 100% minus the width of all the other columns (which are automatically-sized). It also needs a vertical-align: top as otherwise the (empty) outer div is aligned middle, so the absolutely-positioned element will be off by half a line.

Here is a full example with a three-column, two-row table showing this at work:

CSS:

div.outer {
    position: relative;
}
div.inner {
    overflow: hidden;
    white-space: nowrap;
    position: absolute;
    width: 100%;
}
table {
    width: 100%;
    border-collapse: collapse;
}
td {
    border: 1px dotted black;
    vertical-align: top;
}
col.fill-the-rest { width: 100%; }

HTML:

<table>
    <col><col><col class="fill-the-rest">
    <tr>
        <td>foo</td>
        <td>fooofooooofooooo</td>
        <td>
            <div class="outer">
                <div class="inner">
                    Long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>barbarbarbarbar</td>
        <td>bar</td>
        <td>
            <div class="outer">
                <div class="inner">
                    Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text Some more long text
                </div>
            </div>
        </td>
    </tr>
</table>

In this example, the first two columns will have the minimum possible size (i.e. spaces will make them wrap a lot unless you also add white-space: nowrap to them).

jsFiddle: http://jsfiddle.net/jLX4q/

Leave a Comment