CSS 解决多层Flex布局元素滚动失效

2,295 阅读1分钟

解决使用多层flex布局,内层元素滚动失效问题

问题

例如想实现效果:

image.png

结果却变成这个样子:

image.png

html结构

<div class="root">
  <div class="box">
    <div class="left">左侧布局</div>
    <div class="right">
      右侧布局
      <div class="scorll-box">
        <div class="scorll-content">滚动内容</div>
      </div>
    </div>
  </div>
</div>

样式

.root {
  display: flex;
  width: 400px;
  height: 400px;
  border: 1px solid #000;
  overflow: auto;
}
.box {
  flex: 1;
  display: flex;
}
.left {
  width: 150px;
  height: 100%;
  background: pink;
}
.right {
  flex: 1;
  height: 100%;
  background: #0cc;
  overflow: auto;
}
.scorll-box {
  width: 100%;
  overflow: auto;
}
.scorll-content {
  width: 1000px;
  height: 200px;
  background: linear-gradient(90deg, grey, red);
}

分析

从代码视觉上看

  • .root 是个flex元素同时有固定宽度
  • .box 是个flex元素,完全自适应父级.root大小
  • .left 是 .box 内的子元素有固定宽
  • .right 是个flex元素,完全自适应父级.box大小,同时设置了允许滚动
  • .scorll-box 是个滚动元素盒子,宽度匹配父级.right大小

解决

经过调试发现,flex:1 溢出父级大小,需要在此处增加overflow即可 overflow: hidden|auto|scorll.

image.png

.box {
  overflow: hidden; /* +++ */
}

允许效果: image.png