Yuriy Galanter - 7 months ago 43

HTML Question

Is there a way to autosize HTML table height based on content? Also if it's a cell (or cells) next to a neighbor cell with multiple rowspans.

E.g. if I have a table like this (cell on the right has Rowspan="2" and height of the cell content = 600px, in each cell on the left height of the cell content = 150px):

there is a gap between 2 cell consents on the left because cells themselves autosized their height. I'd like it to look like this:

Where top cells automatically collapse to cell content height. Is there anyway to achieve this?

Answer

This sets the last row of cells to the correct height (demo):

```
function grow(td) {
var table, target, high, low, mid;
td = $(td);
table = td.closest('table');
target = table.height();
low = td.height();
// find initial high
high = low;
while (table.height() <= target) {
td.height(high *= 2);
}
// binary search!
while (low + 1 < high) {
mid = low + Math.floor((high - low) / 2);
td.height(mid);
if (table.height() > target) {
high = mid;
} else {
low = mid;
}
}
td.height(low);
}
$('tr:last-child td').each(function() { grow(this); });
```

It should be trivial to convert this into plain JavaScript.

**Update:** For more complicated tables, you'll want to replace the last line with this (demo):

```
$.each($('td').get().reverse(), function() { grow(this); });
```

The idea is to call `grow()`

on every cell, starting with the last row and working upwards.