Search code examples
htmlcsshtml-table

Setting max-height for table cell contents


I have a table which should always occupy a certain percentage of the height of the screen. Most of the rows are of fixed height, but I have one row that should stretch to fill the available space. In the event that the contents of a cell in that row overflows the desired height, I'll like the contents to clip using overflow:hidden.

Unfortunately, tables and rows do not respect the max-height property. (This is in the W3C spec). When there is too much text in the cell, the table gets taller, instead of sticking to the specified percentage.

I can get the table cell to behave if I specify a fixed height in pixels for it, but that defeats the purpose of having it automatically stretch to fill available space.

I've tried using divs, but can't seem to find the magic formula. If I use divs with display:table, :table-row, and :table-cell the divs act just like a table.

Any clues on how I can simulate a max-height property on a table?

<head>
    <style>
        table {
            width: 50%;
            height: 50%;
            border-spacing: 0;
        }
        td {
            border: 1px solid black;
        }
        .headfoot {
            height: 20px;
        }
        #content {
            overflow: hidden;
        }
    </style>
</head>
<body>
<table>
    <tr class="headfoot"><td>header</td></tr>
    <tr>
        <td>
        <div id="content">
            put lots of text here
        </div>
        </td>
        <tr>
    <tr class="headfoot"><td>footer</td></tr>
</table>
</body>

Solution

  • We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.

    We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.