子Flexbox元素高度超出父容器,滚动条未正常显示求助
Flex布局滚动条不出现问题的解决方法
问题出在父flex容器默认高度为auto,会被内部最高的子元素撑开,导致左侧子容器的高度跟着内容无限延伸,overflow-y: auto自然触发不了滚动。要实现父容器高度贴合右侧固定高度子元素、左侧内容超出就滚动的效果,用下面的纯CSS方法就能解决:
修改后的代码
<div style="display: flex; height: min-content;"> <div style="display: flex; flex-direction: column; flex-grow: 1; overflow-y: auto; min-height: 0; height: 100%;"> <div style="height: 500px; background-color: red;"> Large element with dynamic height. Scrollbar should appear when height is more than blue box. </div> </div> <div style="display: flex; flex-direction: column; flex-shrink: 0;"> <div style="width: 200px; height: 200px; background-color: blue;"> Small element with fixed height </div> </div> </div>
核心改动说明
- 给父flex容器加
height: min-content:强制父容器高度取内部子元素的最小内容高度(也就是右侧的200px),不会再被左侧的高内容撑开。 - 给左侧子容器补
height: 100%:让左侧子容器高度和父容器保持一致(200px),内容超过这个高度就会触发垂直滚动。 - 给右侧子容器加
flex-shrink: 0:防止右侧子容器在空间不够时被压缩,保证它的固定宽高不受影响。
这样改完之后,父容器高度就会贴合右侧的200px,左侧子容器被限制在200px高度内,内部的红色元素超出部分会显示滚动条,完全符合需求。
内容的提问来源于stack exchange,提问作者Stanton
相关产品推荐
相关产品推荐

