Search code examples
cssflexboxoverflow

CSS Flexbox Layout with Nested Scrollable Section


I'm working on a layout using CSS Flexbox where I need to achieve a specific structure with a main container and nested children, each serving different parts of the UI. The main goal is to have a scrollable section within a nested child element, without causing the overall page layout to exceed the viewport height. Here's the structure I'm aiming for:

  • A main container with a height of 100vh.
    • A topbar with a fixed height of 80px.
    • A flex container (let's call it content-area) designed to take up the remaining space with flex-grow: 1.
      • Within content-area, an aside element that spans the full height of its parent.
        • The aside contains two children:
          1. A div that should expand with flex-grow: 1 to fill the available space.
          2. Another div with a fixed height of 140px.
          • Inside this expandable div, there's an h3 followed by a div with a class .filter-bar--scrollable-section. I want this div to occupy all available space and have a overflow-y to handle content that exceeds its remaining height.
    • A bottombar with a fixed height of 80px.

Here's a simplified version of my HTML structure:

<main class="main">
  <div class="topbar">Topbar Content</div>
  <div class="content-area">
    <aside>
      <div class="expandable-area">
        <h3>Title</h3>
        <div class="filter-bar--scrollable-section">
          <!-- Dynamic content here -->
        </div>
      </div>
      <div class="fixed-area" style="height: 140px;">
        Fixed Height Content
      </div>
    </aside>
  </div>
  <footer style="height: 80px;">Footer Content</footer>
</main>

And the CSS:

.main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.content-area {
  flex-grow: 1;
  display: flex;
}

aside {
  height: 100%;
}

.expandable-area {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.filter-bar--scrollable-section {
  /* How should I style this? */
}

I've attempted to set flex-grow: 1 on the .expandable-area to make it fill the available space, and I want the .filter-bar--scrollable-section to fill the remaining space within .expandable-area and be scrollable if its content exceeds the space.

How can I style .filter-bar--scrollable-section to achieve this? I've tried various combinations of overflow-y and adjusting flex properties but can't seem to get it right. Any help or pointers would be greatly appreciated!


Solution

  • There will be other solutions, but when you know the exact height of the other areas, I'd probably just use calc to fix its height.

    .expandable-area {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      max-height: calc(100vh - 300px);
    }
    
    .filter-bar--scrollable-section {
      overflow-y:scroll;
    }