Search code examples
jqueryhtmlcsstwitter-bootstrapstylesheet

Restricting tbody to maximum height?


I'd like to enforce a max-height policy on a table's tbody with overflow set to auto, so that a scrollbar only shows up when a table gets too tall.

Is there a way to limit the height of a tbody element within a table, in this way?

My table of interest is dynamically inserted within a cell in a larger table, which is contained within a Bootstrap panel container. Doing the following kind of code did not work:

html = "";
html += "<p>";
html += "<table class=\"sortable target_detail_sortable\" style=\"width:100%;\" id=\"my_div_table\">";
html += "<thead>";
// populate header cells
html += "</thead>";
html += "<tbody style=\"max-height:300px; overflow:auto;\">";
// populate body cells
html += "</tbody>";
html += "</table>";
html += "</p>";
$("#my_div").html(html);

Any usable advice is appreciated, thanks!


Solution

  • You can't set a fixed or maximum height on any table elements. The height property is only treated as a minimum height.

    You can add display: block to your tbody. Since it's no longer one of the table-* display types in that case, that will make it take the height. However, since the tbody is no longer a table-row-group, you'll essentially end up with an implicit table inside it again. So any columns in any other thead, tbody or tfoot elements will no longer line up with that scrollable tbody.

    Apart from the column mismatching, though, this does make it almost work in all the latest browsers except IE. You should be able to fix the remaining issues yourself.

    I have no idea how to fix it in IE, though. I did come across "Pure CSS Scrollable Table with Fixed Header", but that's rather out-dated, since both of his solutions work in IE6, but break horribly in IE7 and IE8 (in different ways too). They do work in IE's Quirks mode, though, so if you desperately need it, that might be your only option.