DEV Community

John Cheng
John Cheng

Posted on

Using overflow:scroll and flexbox to render a vertical list that takes all the available height based on a sibling element

tldr; Here is an implementation of a vertical scrollable list using flexbox that takes the available space set by a sibling element. Vanilla CSS and Tailwind versions.

Code in Sandbox (Contains Vanilla CSS version and Tailwind version)

Use case

We wanted to have a container with 2 columns where:

  1. the left-hand side had a growable textarea and,
  2. the right-hand side had a scrollable list on the y-axis that takes the full height

Requirements

  • The textarea can contain as much text as it wants
  • The scrollable list should use the available height based on textarea and display as many items as possible or overflow:scroll

Challenges

When using flexbox with overflow:scroll and rendered the list of items directly, it would increase the height instead of displaying as many as possible given the height from the left-hand side.


Our solution for the scrollable list

  1. We have a flex wrapper that has the overflow: scroll; property, let's call it container

  2. We added an additional wrapper container around the overflowing list of items with a max-height: 0;, let's call it list-container

  3. We rendered the list of items

Note: If we had rendered the items in container directly, they would have increased its height and not respect the height provided by textarea on the left-hand side.

list-container do not increase the height of container thanks to max-height:0; and as we do not define the overflow behaviour, it defaults to visible. However, as we set overflow:scroll at the container level, we still benefit from the scrolling we wanted.

Final note


I hope you found the post interesting. If you have implemented a similar solution in a more elegant way, please let me know in comments 🙌 This is what we came up with and it's probably not perfect!

Take care everyone 👋

Top comments (1)

Collapse
 
uwqirongsu profile image
UWQirongSu

Very helpful! thank you for the post!