Flex儿童,无包装儿童溢出屏幕

时间:2020-04-06 15:28:07

标签: html css flexbox

我有一个非常具体的flex用例,我不太理解为什么它表现得如此。我有两列。右列的宽度固定为flex-shrink: 0。左列有flex-shrink: 1flex-grow: 1,最重要的是,孩子有width: 100%white-space: nowrapoverflow-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>

1 个答案:

答案 0 :(得分:1)

我通过在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