如何解决使用flexbox布局的父元素意外垂直溢出问题
提问:Flex嵌套布局下父容器非预期溢出问题
我在处理一个封装了列表项容器的样式元素时遇到了问题。
HTML结构
<div id="root"> <div class="app"> <!-- 导致溢出 - 非预期 --> <nav class="appTopbar"></nav> <main class="page"> <nav class="pageTopbar"></nav> <div class="container"> <div class="left"> <nav class="pageTopbar"></nav> <div class="list"> <!-- 导致溢出 - 预期 --> <div class="item">Item 1</div> ... </div> </div> <div class="right"></div> </div> </main> </div> </div>
当.list内积累大量条目时就会出现问题。.app、.page、.container、.left元素均使用flexbox布局,方向为垂直主轴:
display: flex; flex-direction: column;
除.left外,其余上述元素均设置了height: 100%或height: inherit属性。
一个不太理想的临时方案是给.page添加overflow: hidden;属性,但我希望能找到更合理的解决办法。
感谢各位抽出时间提供帮助。
可复现溢出问题的示例代码
HTML
<div id="root"> <div class="app"> <nav class="appTopbar"></nav> <main class="page"> <nav class="pageTopbar"></nav> <div class="container"> <div class="left"> <nav class="pageTopbar"></nav> <div class="list"></div> </div> <div class="right"></div> </div> </main> </div> </div>
CSS
html, body { height: 100%; margin: 0; } #root { height: inherit; } * { box-sizing: border-box; } .app { display: flex; flex-direction: column; justify-content: stretch; align-items: stretch; height: inherit; } .appTopbar { display: flex; align-items: center; flex: 0 0 50px; background: #00308F; } .page { display: flex; flex-direction: column; height: 100%; } .container { flex: 1 1; display: flex; height: 100%; } .left { display: flex; flex-direction: column; flex: 0 1 100px; background: #7FFFD4; } .right { flex: 1 1; background: #0066b2; } .list { padding: 10px; overflow-y: auto; flex: 1 1; }
JS
const list = document.querySelector(".list"); let index = 0; for(let it of new Array(100)) { const node = document.createElement("div"); const textnode = document.createTextNode(`Element ${index}`); node.appendChild(textnode); list.appendChild(node); index++; }
回答
根因
该问题由flex布局的默认特性导致:垂直主轴的flex子元素默认min-height值为auto,即子项的最小高度默认等于其内容高度,不受父容器高度限制,因此会被内部的长列表撑开,最终导致外层容器非预期溢出。
修复方案
无需添加overflow: hidden,仅需要给两个flex子项新增min-height: 0覆盖默认值即可:
.page { display: flex; flex-direction: column; height: 100%; min-height: 0; /* 新增 */ } .left { display: flex; flex-direction: column; flex: 0 1 100px; background: #7FFFD4; min-height: 0; /* 新增 */ }
修改后仅.list区域会出现滚动条,外层容器不会溢出,符合预期。
内容的提问来源于stack exchange,提问作者Józef Podlecki
相关产品推荐
相关产品推荐

