滚动时内容高度未自动调整:模态框右列如何适配左列动态高度
解决方案
你需要调整两处核心样式即可实现右列高度随左列自适应:
- 移除外层内容容器的滚动属性,让容器高度由左列内容撑开
- 给右列单独添加滚动属性,内容溢出时仅在右列内部滚动,高度保持和左列一致
修改后的完整CSS代码如下:
.Container { margin: auto auto; width: 80vw; /* 移除固定高度,让容器整体高度由内容决定 */ /* height: 250px; */ background-color: #8080801a; display: flex; flex-direction: column; } .Header { height: 50px; width: 100%; background-color: #61dafb; } .FlexContainer { flex: 1; display: flex; /* 移除外层容器的滚动属性 */ /* overflow: auto; */ } .LeftSection { width: 200px; /* 这里的400px是示例高度,替换为动态内容后高度会自动计算 */ height: 400px; background: red; flex-shrink: 0; /* 避免左列被挤压变形 */ } .RightSection { flex: 1; /* 自动占满剩余宽度,替换原有的width:100% */ background-color: black; overflow: auto; /* 内容溢出时右列单独滚动,高度和左列保持一致 */ } .Footer { height: 50px; background-color: blue; width: 100%; }
HTML只需要修正Footer的闭合标签即可(div不支持自闭合写法):
<div class="Container"> <div class="Header"></div> <div class="FlexContainer"> <div class="LeftSection" ></div> <div class='RightSection' ></div> </div> <div class='Footer'></div> </div>
实现原理
Flex布局的父容器默认开启align-items: stretch属性,子元素会自动撑满父容器的高度。我们让FlexContainer的高度完全由左列内容撑开,右列就会自动适配和左列相同的高度。
内容的提问来源于stack exchange,提问作者Razvan
相关产品推荐
相关产品推荐

