Reputation: 2901
I'm trying to create a list inside a div bounded by max-height
. If the list is longer than it's parent's max-height (less padding), the list should scroll.
I can make this scenario work if I put the max height directly on the list itself. It's nested because the outer container, which max height is attached to, contains areas which shouldn't scroll. I've demonstrated this using padding.
I've tried various configurations but the list either doesn't show a scroll bar or overflows its parent. I can make it work if I put the min-height on the list itself, but this means taking into account the 'non scrolling' areas, which means it would be subject to change/and breaking in future.
The snippet contains two examples. The first, showing where I am right now, and the second example with max-height set on the list, just to show what I'm trying to achieve.
Any ideas?
.container {
margin: 50px;
}
.fixed {
background-color: lime;
padding: 20px 0;
}
.scroll {
background-color: red;
overflow-y: auto;
}
li {
height: 60px;
}
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll">
<li>This doesn't work!</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll" style="max-height:160px">
<li>This is to demonstrate what I'm trying to achieve.</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
Upvotes: 2
Views: 1174
Reputation: 274272
Make the fixed element a flexbox container:
.container {
margin: 50px;
}
.fixed {
background-color: lime;
padding: 20px 0;
display:flex;
}
.scroll {
background-color: red;
overflow-y: auto;
width:100%;
}
li {
height: 60px;
}
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll">
<li>This doesn't work!</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll" style="max-height:160px">
<li>This is to demonstrate what I'm trying to achieve.</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
Upvotes: 2
Reputation: 314
I have changed your first code where you wrote It doesn't work (UPDATED)
.container {
margin: 50px;
}
.fixed {
background-color: lime;
padding: 20px 0;
}
.scroll {
background-color: red;
overflow: auto;
height: 100%;
max-height: 150px;
}
li {
height: 60px;
}
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll">
<li>This doesn't work!</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
<div class="container">
<div class="fixed" style="max-height:200px">
<ul class="scroll" style="max-height:160px">
<li>This is to demonstrate what I'm trying to achieve.</li>
<li>Line 2</li>
<li>Line 3</li>
<li>Line 4</li>
</ul>
</div>
</div>
Upvotes: 0