如何为CSS Grid行强制设置max-height并实现列表滚动
解决CSS Grid max-height被列表项撑开的问题
问题核心是你给Grid第二行设置了min-content,这会让该行高度完全由内部内容决定,直接突破Grid的max-height限制。要让max-height生效并实现列表区域滚动,需调整以下几点:
- 修改Grid行高规则:把
grid-template-rows: 50px min-content改成grid-template-rows: 50px 1fr,让第二行自动占据Grid剩余可用空间,不再被内容撑开。 - 约束列表父容器高度:给
.three设置height: 100%,确保它的高度被Grid行限制,内部的.body才能正确继承高度并触发滚动。 - 调整滚动容器高度:把
.body的max-height: 100%改成height: 100%,确保它填满父容器的可用空间,滚动条正常工作。
修改后的完整代码如下:
HTML代码
<div class="grid"> <div class="two"> Two </div> <div class="three"> <div class="body"> <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>
CSS代码
.grid { display: grid; grid-template-rows: 50px 1fr; /* 改用1fr分配剩余空间 */ max-height: 300px; background: blue; overflow-y: hidden; } .two { background: green; } .three { background: #00000044; height: 100%; /* 强制继承Grid行的高度 */ } .body { max-width: 400px; background: orange; margin: auto; height: 100%; /* 填满父容器高度 */ overflow-y: scroll; }
修改完成后,Grid的max-height会严格生效,当列表内容超过剩余空间时,.body区域会自动出现垂直滚动条,整个Grid不会被内容撑开。
内容的提问来源于stack exchange,提问作者Pierre Olivier Tran
相关产品推荐
相关产品推荐

