htmlcssflexbox

Prevent div to grow in flex mode


I have read a lot of posts facing this issue, and no solution works for me. The problem is very simple. Here is an overview of the structure:

<div id=mainDiv>
  <div id=banner></div>
  <div id=expectedDivWithScrollBar>
    <table> Very height table </table>
  </div>
</div>

I have expectedDivWithScrollBar that takes the remaining height available (under a banner) of the viewport with:

display:flex;
flex: 1 0 auto;

Now, in this div, I have a table that can become bigger than the div. I would like to have a scrollbar in that div, and NOT in the main div, because I don't want scroll the banner.

Without the table, the dimension of expectedDivWithScrollBar are perfect, automatically computed.

I though that adding "overflow: auto" in expectedDivWithScrollBar would have solve the issue, but it has no effect. flew-shrink to 0 doesn't work as well.

All the solutions I saw seems to rely on setting a size on expectedDivWithScrollBar (Or one of his parents), but that's not acceptable. Everything is dynamically sized...

Thanks for your help!


Solution

  • How about changing the #mainDiv to be a flex container with flex-direction: column?

    This way you could make sure that the table only takes the remaining space under your banner.

    In the runnable example below I've marked the banner red and the table blue, as you can see, the table is scrollable in height and would not affect the rest of your layout.

    #mainDiv {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    
    #banner {
      height: 40px;
      flex: 0 0 auto;
      background: red;
    }
    
    #expectedDivWithScrollBar {
      flex: 1 1 auto;
      overflow: auto;
    }
    
    table {
      height: 120vh;
      background: blue;
    }
    <div id=mainDiv>
      <div id=banner>Banner</div>
      <div id=expectedDivWithScrollBar>
        <table>
          <tr>
            <th>Company</th>
            <th>Contact</th>
            <th>Country</th>
          </tr>
          <tr>
            <td>Alfreds Futterkiste</td>
            <td>Maria Anders</td>
            <td>Germany</td>
          </tr>
          <tr>
            <td>Centro comercial Moctezuma</td>
            <td>Francisco Chang</td>
            <td>Mexico</td>
          </tr>
        </table>
      </div>
    </div>