Flex主轴方向子项溢出问题:动态info容器滚动实现咨询
解决方案
要实现你想要的效果,纯Flex布局就能搞定,不需要依赖calc或固定尺寸。核心是利用Flex的空间分配特性,让info容器自动占据overlay的剩余垂直空间,同时给内容容器设置滚动规则。
修改后的代码
HTML(无需改动)
<div class="display"> <div class="overlay"> <div class="info"> <button id="close-info">Close</button> <div class="info-content-wrapper"> <div class="content"></div> </div> </div> <div class="controls"> <button id="open-info">Open info</button> <button id="increase-height">+</button> <button id="decrease-height">-</button> </div> </div> </div>
CSS(关键修改)
.display { position: relative; width: 400px; height: 300px; background-color: gray; } .overlay { position: absolute; display: flex; width: 100%; height: 100%; top: 0; left: 0; flex-direction: column; align-items: flex-end; /* 保持子元素右对齐 */ /* 移除justify-content: flex-end,让Flex自动分配剩余空间 */ } .info { display: flex; flex-direction: column; align-items: flex-end; /* 内部元素右对齐 */ flex: 1; /* 占据overlay除controls外的所有剩余垂直空间 */ background-color: orange; padding: 10px; /* 移除固定max-height和flex-shrink:0,让容器动态适配空间 */ } .info-content-wrapper { padding: 5px; overflow-x: hidden; overflow-y: auto; flex: 1; /* 占据info除关闭按钮外的剩余空间 */ width: 100%; /* 确保内容容器宽度适配 */ } .content { width: 80px; height: 150px; background-color: yellow; } .controls { background-color: lightblue; padding: 5px; flex: 0 0 auto; /* 固定高度,不参与空间分配 */ }
JavaScript(无需改动)
const info = document.querySelector(".info"); const content = document.querySelector(".content"); document.querySelector("#open-info").addEventListener("click", () => { info.style.display = "flex"; }); document.querySelector("#close-info").addEventListener("click", () => { info.style.display = "none"; }); document.querySelector("#increase-height").addEventListener("click", () => { content.style.height = `${content.clientHeight + 30}px`; }); document.querySelector("#decrease-height").addEventListener("click", () => { content.style.height = `${content.clientHeight - 30}px`; });
关键修改说明
- .overlay:移除
justify-content: flex-end,让Flex布局自动将剩余空间分配给.info(因为.info设置了flex:1),同时保留align-items: flex-end确保所有子元素右对齐。 - .info:用
flex:1替代固定max-height,使其高度自动等于.overlay总高度减去.controls的高度,完美利用剩余垂直空间;移除flex-shrink:0,让它能正常参与Flex空间分配。 - .info-content-wrapper:添加
flex:1,使其填充.info中除关闭按钮外的所有剩余空间,配合overflow-y:auto,当内容高度超过该空间时自动触发滚动,同时保证.info不会超出.overlay的范围。
内容的提问来源于stack exchange,提问作者panda-byte
相关产品推荐
相关产品推荐

