Scroll inside multiple nested flexboxes

Viewed 112

This is what I have:

This is what I want:

So the whole content of 'Container 5' should be visible without scroll. The height of 'Container 2' should be only dependent on the height of 'Container 5'. 'Container 4' should be scrollable if it has more content than 'Container 5'. The content of 'Container 5' is dynamic - I don't know it's height. 'Container 3' should fulfill the whole available screen space at the bottom.

This is code: https://jsfiddle.net/antonfil/5kd1gnou/13/

Any ideas how to do it?

JavaScript solutions are fine but it's also interesting if it is possible to achieve it with pure CSS.

3 Answers

change style of container-2,container-4 and container-5 as below.

#container-4 {
  display: flex;
  overflow-y:auto;
  flex: 1 0;
  background-color: yellow;
}
#container-5 {
  display: flex;
  flex: 1 0;
  height:min-content;
  background-color: orange;
}

here we set the height of container-5 as the minimum height. And set a vertical overflow as scroll for container-4. Then adjust the height of container-4 dynamically using Jquery.

add this script to your HTML file.

<script>
$(document).ready(function(){
    let height=$("#container-5").height();
   $("#container-4").height(height);
});
</script>

And don't forget to add Jquery to your HTML.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

add this script

  <script>
        document.addEventListener("DOMContentLoaded", () => {
            const container_5 = document.querySelector('#container-5');
            const container_4 = document.querySelector('#container-4');
            container_4.style.height = container_5.offsetHeight + 'px';
        });
    </script>

and change #container-4 css to:

#container-4 {
    display: flex;
    height: 0;
    flex: 1 0;
    overflow-y: auto;
    background-color: yellow;
}

the script above will set the height of #container-4 to the calculated height of #container-5. by doing this you don't need a 'predefined' size for any of the containers.

To container 2, try to add overflow: scroll;.

Related