flex 嵌套下 overflow: hidden 失效
HTML结构
<div class="container"> <div class="header">header</div> <div class="main"> <div class="left">left</div> <div class="center"> <div class="item">flex 布局下 overflow: hidden 失效1</div> <div class="item">flex 布局下 overflow: hidden 失效2</div> <div class="item">flex 布局下 overflow: hidden 失效3</div> <div class="item">flex 布局下 overflow: hidden 失效4</div> <div class="item">flex 布局下 overflow: hidden 失效5</div> <div class="item">flex 布局下 overflow: hidden 失效6</div> <div class="item">flex 布局下 overflow: hidden 失效7</div> <div class="item">flex 布局下 overflow: hidden 失效8</div> <div class="item">flex 布局下 overflow: hidden 失效9</div> </div> <div class="right">right</div> </div> <div class="footer">footer</div> </div>
CSS代码
.container{ display: flex; flex-direction: column; width: 100vw; height: 100vh; color: #333; background-color: #f3f3f3; overflow: hidden; .header, .footer{ height: 80px; font-size: 24px; display: flex; justify-content: center; align-items: center; background-color: #dee2e6; } .main{ flex: 1; display: flex; .left, .right{ width: 30%; font-size: 24px; display: flex; justify-content: center; align-items: center; background-color: #adb5bd; } .center{ flex: 1; overflow: hidden; .item{ height: 40px; line-height: 40px; font-size: 20px; } } } }
效果
缩小了浏览器,可以看到 footer 被挤没了,header 也变小了,现在的 overflow 其实是 container 的,并不是 center 的
解决方案:
在 center 下再包一层,然后将 center 设置 position: relative,并将添加的层设置 position: absolute;width: 100%;height: 100%;使得新添加的层撑满 center
<div class="center"> <div class="content"> <div class="item">flex 布局下 overflow: hidden 失效1</div> <div class="item">flex 布局下 overflow: hidden 失效2</div> <div class="item">flex 布局下 overflow: hidden 失效3</div> <div class="item">flex 布局下 overflow: hidden 失效4</div> <div class="item">flex 布局下 overflow: hidden 失效5</div> <div class="item">flex 布局下 overflow: hidden 失效6</div> <div class="item">flex 布局下 overflow: hidden 失效7</div> <div class="item">flex 布局下 overflow: hidden 失效8</div> <div class="item">flex 布局下 overflow: hidden 失效9</div> </div> </div>
.center{ flex: 1; overflow: hidden; position: relative; .content{ position: absolute; width: 100%; height: 100%; .item{ height: 40px; line-height: 40px; font-size: 20px; } } }
效果