Flex项目在flex-basis下缩小

3

我一直在阅读 Stack Overflow 的问题和其他博客,试图理解 flex-basis 是什么,但我仍然无法完全理解它如何影响元素的行为。

这是我的代码示例:

.item {
  background-color: red;
  border: 1px solid pink;
  margin: 10px;
  padding: 10px;
}

.container {
  display: flex;
}

.container .item {
  height: 50px;
  flex-grow: 1;
}

.container3 {
  flex-direction: row;
  width: 500px;
}

.container3 .a,
.container3 .b {
  flex-basis: 200px;
}
<div class="container container3">
  <div class="item a">Segmentation fault</div>
  <div class="item b">Null pointer exception</div>
  <div class="item c">hello</div>
  <div class="item d">hello</div>
</div>

我将项 abflex-basis 设置为 200px,但它们的宽度都小于 200px。我原本认为 flex-basis 是项的“初始”宽度,即项的“最小宽度”。但显然这不是真的,所以我不明白“初始”是什么意思。
当给出像素值的 flex-basis 时,计算项 ab 的宽度的具体数学公式是什么?
1个回答

6
一个弹性容器的初始设置是 flex-shrink:1
这意味着为了避免溢出容器,弹性项目允许收缩。
一旦你禁用了这个功能,弹性项目将不会收缩到小于其指定的 flex-basis 值。

* { flex-shrink: 0; } /* NEW */

.item {
  background-color: red;
  border: 1px solid pink;
  margin: 10px;
  padding: 10px;
}

.container {
  display: flex;
  border: 1px dashed black;
}

.container .item {
  height: 50px;
  flex-grow: 1;
}

.container3 {
  flex-direction: row;
  width: 500px;
}

.container3 .a,
.container3 .b {
  flex-basis: 200px;
}
<div class="container container3">
  <div class="item a">Segmentation fault</div>
  <div class="item b">Null pointer exception</div>
  <div class="item c">hello</div>
  <div class="item d">hello</div>
</div>

我将项目a和b的flex-basis设置为200像素,但它们的宽度都小于200像素。我原以为flex-basis是项的“初始”宽度,意思是项的“最小宽度”,但显然这不是真的,所以我不明白“初始”是什么意思。
实际上,这是正确的。flex-basis设置了项的初始长度。您定义的项目的初始宽度为200像素。然后应用flex-shrinkflex-grow
当给flex-basis一个像素值时,计算公式如下:

1
正如我的问题所述,我看到.item.a的宽度为156px。你知道用于确定这个值的数学公式是什么吗?为什么是156px而不是152px或任何其他值?我问这个问题是因为我正在尝试预测当未指定flex-shrink时,flex-basis对元素的影响。 - John
请查看我回答末尾的链接。 - Michael Benjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接