I’d like to have a card with a fixed header, and scrollable contents.
I’ve figured out how to do something similar by setting a fixed height to the card, and using overflow scrolling.
<div class="card">
<div class="sticky-header">
<!-- title -->
</div>
<div class="overflow-contents">
<!-- contents -->
</div>
</div>
.card {
height: calc(100vh - 32px);
display: flex;
flex-direction: column;
overflow: scroll;
}
.sticky-header {
display: sticky;
top: 0px;
}
.overflow-contents {
display: flex;
flex-wrap: wrap;
}
https://codepen.io/david-schultz/pen/mdQobQV
However, what I’m actually trying to achieve is to have something like flexible card height. I.e. the card’s height depends on the amount of overflowing content. (I’m not sure if this is actually how to solve this problem, but it’s the mental model I have right now.)
2
Answers
Just remove your
height
rules?If you want a card with a fixed header and a scrollable content area, and you want the card’s height to be flexible depending on the amount of overflowing content, you can achieve this using CSS Flexbox and setting the overflow property appropriately. Here’s how you can modify your existing code to achieve the desired effect:
With the updated CSS, the .card container is now a flex container, and the .overflow-contents div is given flex: 1, which allows it to take up the remaining vertical space. When the content inside .overflow-contents exceeds the available space, it will automatically start scrolling.
The overflow: hidden is still applied to the .card, but the .overflow-contents div will expand to accommodate the content, and any overflowing content will be scrollable within this div.
With this approach, the height of the card will be flexible and adapt to the content inside the .overflow-contents div, while keeping the header (.sticky-header) fixed at the top of the card.