How to make a scrollable container with dynamic height using Flexbox
One of the hidden features of Flexbox is the ability to make a flex child scrollable. In the past, if you wanted to make a scrollable container, you had to give the container a predefined height. In other words, the height could not be based on the size of its surrounding content. You had to use pixels, percentages, or absolute positioning if you wanted an element’s content to scroll.
With Flexbox, we can now create scrollable containers whose size depends on the available space after the rest of the content has been laid out.
The key is to use Flexbox for all containers that wrap the scrollable container, and give the outermost container a predefined height. Since content lays vertically on the page by default, I recommend making each container use the vertical (column) flex layout rather than the default horizontal (row) layout.
There’s a special case where the min-height of flex items defaults to the content size rather than zero. According to the spec, this should only apply when overflow is set to visible. For whatever reason, Firefox doesn’t implement it this way (as of 52.0.1 on Mac), and apparently thinks Chrome has it wrong. So for now, we have to explicitly set the min height to zero, or else the content will overflow its parent even though we’ve set it to scroll. This step needs to be done for every flex-item parent all the way up to the outermost flex-box.
I also like to set “flex-grow: 1” for each flex-item parent so that the remaining vertical space is always filled. But this isn’t necessary.
Live demo: https://codepen.io/stephenbunch/pen/KWBNVo