首页 > 解决方案 > 带有无包装子元素的 Flex 子元素溢出屏幕

问题描述

我有一个非常具体的 flex 用例,我不太明白它为什么会这样。我有两列。右列具有固定宽度,并且flex-shrink: 0. 左列有flex-shrink: 1, flex-grow: 1, 和,关键的是,一个孩子有width: 100%, white-space: nowrap, 和overflow-x: scroll

我期望的是左列填充剩余的宽度,然后溢出滚动。然而,实际发生的是左列将右列推离屏幕。

你可以在这里看到一个例子:https ://codepen.io/benlorantfy/pen/oNXKXOe

我正在寻找解释它为什么会这样以及我可以做些什么来解决它。

.flex-parent {
  display: flex;
  flex-direction: row;
}

.flex-child-1 {
  background-color: red;
  height: 200px;
  flex-grow: 1;
  flex-shrink: 1;
}

.nowrap-el {
  white-space: nowrap;
  width: 100%;
  overflow-x: scroll;
  background-color: grey;
}

.flex-child-2 {
  background-color: lightblue;
  height: 200px;
  width: 400px;
  flex-shrink: 0;
}
<div class="flex-parent">
  <div class="flex-child-1">
    <div class="nowrap-el">
      This should fill remaining space instead of pushing flex-child-2 off the screen. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas in augue volutpat, sagittis ante et, tincidunt mauris. Morbi vitae convallis erat, eget vulputate lacus.
      Nunc a justo aliquet, facilisis justo eget, semper velit. Nunc quis elementum tortor. Nam vestibulum aliquet nunc, id
    </div>
  </div>
  <div class="flex-child-2">This should not be shoved off screen</div>
</div>

标签: htmlcssflexbox

解决方案


我通过添加overflow-x: hidden来解决这个问题flex-child-1。(我也添加flex-basis: 0了很好的措施,但我认为它没有任何作用)。这似乎告诉浏览器尊重孩子的宽度和溢出设置。我不确定为什么会这样,或者规范中的哪个地方这么说,但如果有人知道并想发表评论,请随意。

.flex-child-1 {
  background-color: red;
  height: 200px;
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  overflow-x: hidden;
}

查看现场演示:https ://codepen.io/benlorantfy/pen/ExjqJBM


推荐阅读