Flex items are shrinking below flex-basis

我的未来我决定 提交于 2021-02-05 06:40:26

问题


I've been reading stack overflow questions and other blogs on what flex-basis is supposed to do, but I still can't fully grasp how it affects the behaviour of an element.

Here's an example with my code:

.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>

I set flex-basis to 200px for items a and b but they are both shorter than 200px width. I was under the impression that flex-basis is the "initial" width of the item, meaning "min-width" of an item. But clearly that's not true, so I don't understand what "initial" means.

What is the specific mathematical formula that calculate the width of item a and b when a pixel value is given for flex-basis?


回答1:


An initial setting of a flex container is flex-shrink: 1.

This means that flex items are allowed to shrink in order to not overflow the container.

Once you disable this feature, flex items won't shrink below their specified flex-basis values.

* { 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>

I set flex-basis to 200px for items a and b but they are both shorter than 200px width. I was under the impression that flex-basis is the "initial" width of the item, meaning "min-width" of an item. But clearly that's not true, so I don't understand what "initial" means.

Actually, it is true. flex-basis sets the initial length of the item. The initial width of your items is 200px, as you defined. Then flex-shrink and flex-grow are applied.

What is the specific mathematical formula that calculate the width of item a and b when a pixel value is given for flex-basis?

The calculations are explained here:

  • How does flex-shrink factor in padding and border-box?


来源:https://stackoverflow.com/questions/48209955/flex-items-are-shrinking-below-flex-basis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!