I’m trying to create a container that automatically adjusts its height based on content, but never exceeds a specific maximum value (let’s say 150px for this example). When the content is shorter than 150px, the container should shrink to fit the content. When content is taller than 150px, the container should stay at 150px and allow scrolling.
I thought something like this would work:
height: min(fit-content, 150px);
This would mean “use the smaller value between content height and 150px”. Unfortunately, this approach isn’t supported by browsers.
I tried using max-height
and min-height
instead of setting a fixed height
, but then I lose the scrolling capability when content overflows.
Here’s my current HTML structure (I need to keep this three-div layout):
<div style="position: absolute;
border: 2px solid gray;
box-sizing: border-box;
width: 12rem;
height: 150px;
max-height: 150px;
min-height: fit-content;">
<div style="position: relative;
width: 100%;
height: 100%;">
<div style="height: 100%; width: 100%; overflow-y: scroll;">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
<div>Item 8</div>
</div>
</div>
</div>
How can I achieve this behavior while keeping the scroll functionality intact?