Search code examples
htmlcsscss-tables

How to make one column define table's height while the other will always have scrollbar?


I have this problem at hand:

I have table with two columns. I want the left column to:

  • Define height of the whole table
  • AND at the same time have min-height of 300px

The second column will have much more lines than the left column but it will neither overflow nor expand the whole table (as the height of the table should be defined by left column and right column must never expand the height of the column).

So basically if first columns content is small (let's say two lines) the height of the table will be 300px and the right columns content will have scrollbar as its contents height is over 300px.

small-left-columns

Now next time you load the same page the first column will have more lines, so that their height is over 300px. The table's height will now get bigger so that it is as big as the content of the left column (and therefore left column will never have scrollbar) and right column will again be of appropriate size (same as left column) but again its content will get trimmed and the column will have scrollbar to view the rest of right column.

big-left-column

Could please anyone help me or point me in right direction? I've already spent two hours Googling and trying stuff but I just can't get it working. Also it doesn't have to be achieved with table only. Just divs are also fine. I only need two blocks of text next to each other, 100% width of parent div and height set by left column (while not being less than 300px).


Solution

  • Here's a working example (adjust to your needs) https://jsfiddle.net/aymckoLt/22/

    My solution uses a table and divs in the 2 columns:

    <table border=1>
      <tr>
        <td>
          <div> <!-- actually this div is unnecessary  -->
            <!-- add some of lines -->
          </div>
        </td>
        <td style="height:300px">
          <div style="height: 100%;overflow-y: auto;">
            <!-- add a bunch of lines -->
          </div>
        </td>
      </tr>
    </table>
    

    Hope it meets your requirements.
    Late edit
    Trying to explain what happens ...

    • Setting the height "fixed" on the right column plays the role of "min-height" when the content of the left column it would be less then that height and at the same time gives a "boundary box" for the 100% of the div with the overflow.
    • When the content of the left column, which has no boundaries/limits, it occupies more than that height it makes the cell (td) expand and with it it expands the cell on the right column also (kind of overriding the height specified) and most importantly it's taken in account by the height 100% of the div

    Or to put it simpler ... it's the "magic" of table(s).