为什么 flex-basis: 0 在 chrome 中会中断,宽度为“px”而不是“%”?

问题描述 投票:0回答:1

考虑以下情况:我们有一个弹性容器,它有两个子容器(左子容器和右子容器),这两个子容器应该获得容器宽度的 50%。这是通过将

flex-basis: 0
flex-shrink
flex-grow
设置为 1 来完成的:

.container {
  width: 100%;
  height: 50px;
  background: gray;
  display: flex;
}

.flex-1 {
  flex-basis: 0%;
  flex-shrink: 1;
  flex-grow: 1;
}

.left {
  background: orange;
}

.right {
  background: lime;
}

.bomb {
  background: red;
  width: 1000%;
}
<div class="container">
  <div class="flex-1 left">
    left
    <div class="bomb">
      bomb
    </div>
  </div>
  <div class="flex-1 right">
    right
  </div>
</div>

发生的情况是,虽然“炸弹”的宽度确实是 1000%,正如预期的那样,但它不会导致左侧容器的宽度超过 50%,因为我们有

flex-basis: 0

如果我将
width: 1000%
更改为
width: 1000px
,这仍然成立 - 最后在 Firefox 中:

.container {
  width: 100%;
  height: 50px;
  background: gray;
  display: flex;
}

.flex-1 {
  flex-basis: 0%;
  flex-shrink: 1;
  flex-grow: 1;
}

.left {
  background: orange;
}

.right {
  background: lime;
}

.bomb {
  background: red;
  width: 1000px;
}
<div class="container">
  <div class="flex-1 left">
    left
    <div class="bomb">
      bomb
    </div>
  </div>
  <div class="flex-1 right">
    right
  </div>
</div>

在 Chrome 中,这会导致元素宽度超过 50%。 chrome 是否出于某种原因忽略了 flex-basis ?这是一个错误吗?

尽管如此,实际的问题是我需要设置炸弹的高度并让宽度通过“纵横比”计算(允许其通过100%)。这显然会导致与将宽度设置为大像素相同的问题。

对于上下文:我希望左右面板大小相同,并且我构建了一个“缩放功能”,它允许缩放“炸弹”元素(保留纵横比)。

编辑:似乎“overflow-x:auto;”左侧容器有助于保留布局,但我不确定是否可以将其集成到我的案例中,因为它会导致其他问题,所以我仍然对上面的问题感到好奇。

html css
1个回答
0
投票

使用

px
将为您的元素提供最小尺寸,以防止
flex-shrink
缩小到超过该尺寸
%
不会这样做,因为百分比需要一个引用来解析,而该引用是父元素(包含块),因此父元素将首先获取元素将用作引用的
50%
宽度。

正如您所发现的,使用溢出将禁用收缩约束,与使用

min-width: 0

相同

.container {
  width: 100%;
  height: 50px;
  background: gray;
  display: flex;
}

.flex-1 {
  flex-basis: 0%;
  flex-shrink: 1;
  flex-grow: 1;
  min-width: 0;
}

.left {
  background: orange;
}

.right {
  background: lime;
}

.bomb {
  background: red;
  width: 1000px;
}
<div class="container">
  <div class="flex-1 left">
    left
    <div class="bomb">
      bomb
    </div>
  </div>
  <div class="flex-1 right">
    right
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.