Search code examples
htmlhtml-tableword-wrap

How to wrap long HTML table cell


I have a table with two rows. The second row consists of a long text in a colspan="2". How can this text be wrapped so the table is not wider then the two first row cells? I can't set a fixed width for the table, because the first two cells are dynamic.

http://jsfiddle.net/qLpuq/1/

<table>
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td colspan="2" style="width: 0" >Very long cell that should just be as long as the first two cells and wrap, but not take all the screen width.</td>
    </tr>
</table>

I wrongly assumed, that style="width: 0" would work on that cell.


Solution

  • I’m afraid there’s no direct solution. You could play with JavaScript, creating copy of the table containing only the first row, get its width, discard the copy, and use the width to set the width of your real table. Combined with the setting table-layout: fixed, this should handle the situation. You can simplify the approach so that you do not create a copy of the table but instead remove the second row, later add it back. It gets rather ugly:

    <!doctype html>
    <title>Hack</title>
    <style>
    table { table-layout: fixed }
    tr:first-child td { white-space: nowrap }
    </style>
    <table id=tbl>
    <tbody id=tbody>
        <tr>
            <td id=cell1>Cell 1</td>
            <td id=cell2>Cell 2</td>
        </tr>
        <tr id=row2><td colspan=2>
            Very long cell that should just be as long as the first two cells and
            wrap, but not take all the screen width.
    </table>
    <script>
    var tbl = document.getElementById('tbl');
    var tbody = document.getElementById('tbody');
    var row2 = document.getElementById('row2');
    var cell1 = document.getElementById('cell1');
    var cell2 = document.getElementById('cell2');
    tbody.removeChild(row2);
    var width = tbl.clientWidth;
    var width1 = cell1.clientWidth;
    var width2 = cell2.clientWidth;
    tbody.appendChild(row2);
    cell1.style.width = width1 + 'px';
    cell2.style.width = width2 + 'px';
    tbl.style.width = width + 'px';
    </script>
    

    A completely different idea is to use a workaround where the long text is not in a cell but in a caption element, placed at the bottom of the table:

    <table>
        <caption align=bottom style="text-align: left">
            Very long cell that should just be as long as the first two cells and
            wrap, but not take all the screen width.
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
    </table>