I have a simple grid with 2 rows: one serves as a header, the other one is a list of items. I want my grid to have a max height, and I want to be able to scroll my list of items.
<div >
<div >
Two
</div>
<div >
<div >
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
</div>
</div>
</div>
.grid {
display: grid;
grid-template-rows: 50px min-content;
max-height: 300px;
background: blue;
overflow-y: hidden;
}
.two {
background: green;
}
.three {
background: #00000044;
max-height: 400px;
}
.body {
max-width: 400px;
background: orange;
margin: auto;
max-height: 100%;
overflow-y: scroll;
}
My .grid item has a max height, but still, if I had more items to my list, the whole grid expands. Is there a way to make sure my max height is taken into account ?
CodePudding user response:
If you want to only scroll the list of items and keep the header in the same position you can use position: sticky
, updated example:
.grid {
display: grid;
grid-template-rows: 50px min-content;
max-height: 300px;
background: blue;
overflow-y: auto;
}
.two {
background: green;
position: sticky;
top: 0;
}
.three {
background: #00000044;
}
.body {
max-width: 400px;
background: orange;
margin: auto;
max-height: 100%;
overflow-y: scroll;
}
<div >
<div >
Two
</div>
<div >
<div >
<p>Section first</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section</p>
<p>Section last</p>
</div>
</div>
</div>
CodePudding user response:
instead of overflow hidden use auto
code :
.grid {
display: grid;
grid-template-rows: 50px min-content;
max-height: 300px;
background: blue;
overflow-y: hidden;
}
.two {
background: green;
}
.three {
background: #00000044;
max-height: 400px;
}
.body {
max-width: 400px;
background: orange;
margin: auto;
max-height: 100%;
overflow-y: auto;
}
CodePudding user response:
Is there some reason you can't set max-height to 300px on both .grid and .body ?
.body { max-height: 300px; }