Search code examples
cssflexboxscroll

Scrollbar with dynamic height in css flexbox layout


Let's assume I have a flexbox layout like below.

enter image description here

I want to make the #content div taking all the available space without breaking anything about scrollbar. I tried height: 100% in #content but that pushes the #navbar away from the viewport. What can I do to make this work? Any suggestions? For your convenience, I linked my jsfiddle here.


Solution

  • On of the easiest solutions is to calc() the flex-basis of a content div: subtract flex-basis of #navbar from #container's height.

    #content {
      flex-basis: calc(100vh - 30px);
    }
    

    Snippet:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    #container {
      height: 100vh;
      display: flex;
      flex-direction: column;
    }
    
    #navbar {
      background: red;
      flex-basis: 30px;
    }
    
    #main {
      background: #eee;
      flex-grow: 1;
      display: flex;
    }
    
    #left {
      background: blue;
      flex-grow: 2;
    }
    
    #middle {
      background: #777;
      flex-grow: 1;
      display: flex;
      flex-direction: column;
    }
    
    #content {
      background: #aaa;
      flex-basis: calc(100vh - 30px);
      overflow: auto;
    }
    
    #right {
      background: green;
      flex-basis: 25px;
    }
    <div id="container">
      <div id="navbar"></div>
      <div id="main">
        <div id="left"></div>
        <div id="middle">
          <div id="content">
            <p>paragraph 1</p>
            <p>paragraph 2</p>
            <p>paragraph 3</p>
            <p>paragraph 4</p>
            <p>paragraph 5</p>
            <p>paragraph 6</p>
            <p>paragraph 7</p>
            <p>paragraph 8</p>
            <p>paragraph 9</p>
            <p>paragraph 10</p>
            <p>paragraph 11</p>
            <p>paragraph 12</p>
            <p>paragraph 13</p>
            <p>paragraph 14</p>
            <p>paragraph 15</p>
            <p>paragraph 16</p>
            <p>paragraph 17</p>
            <p>paragraph 18</p>
            <p>paragraph 19</p>
            <p>paragraph 20</p>
          </div>
        </div>
        <div id="right"></div>
      </div>
    </div>