偶然遇见一个奇怪的嵌套Flex问题,当子Flex元素里面的内容宽度过大时,即使指定了overflow:auto,仍然会撑开父元素,导致布局乱掉。一个简单的示例如下:

HTML如下:

<div class="main">
  <div class="left">Sidebar</div>
  <div class="right">
    <div class="label">
      Label
    </div>
    <div class="overflow">      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    </div>
  </div>
</div>

CSS如下:

.main {
  display: flex;
  width: 100%;
}
.left {
  flex: 0 0 160px;
}
.right {
  height: 200px;
  flex: 1;
  background: #ffddaa;
  display: flex;
}
.label {
  flex: 0 0 60px;
}
.overflow {
  flex: 1;
  overflow: auto;
  background: #ddffaa;
}

Chrome / Firefox / Safari 中浏览器底部均出现了非预期的横向滚动条,同时那个 overflow 的滚动条也出现了:

flex虽然会自适应宽度,但是当子元素的宽度过大时,仍然会撑开父元素的宽度,此时只要对子元素做宽度限制即可,比如对 overflow 容器进行宽度限制:

.overflow {
  flex: 1;
  width: 0;
  overflow: auto;
  background: #ddffaa;
}

此时即可正常显示了:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.