0

I need .child-1-2 to grow to its text, but the text overflows. When I change flex-basis of .child-1-1 from 50px to auto, it seems to work. Why is that happening?

.parent-1 {
  display: flex;
}

.child-1 {
  display: flex;
  flex: 0 0 auto;
  background: #4c72af;
}

.child-1-1 {
  display: flex;
  flex: 0 0 50px;
}

.child-1-2 {
  display: flex;
  flex: 1 0 auto;
}

.child-2 {
  display: flex;
  flex: 1 0 auto;
  background: #f7ed7e;
}
<div class="parent-1">
  <div class="child-1">
    <div class="child-1-1">C1</div>
    <div class="child-1-2">Some text</div>
  </div>
  <div class="child-2">
    <div class="child-2-1">Another text</div>
  </div>
</div>
vter
  • 1,881
  • 1
  • 20
  • 38
  • Because `auto` simply allows for a smaller width with this little text content, than a fixed `50px` in combination with the `0` before it actually are. "Be as wide as you need to be, but don't shrink" and "Be 50px wide but/and don't shrink" are just that, different "formulas" saying different things. – CBroe Apr 01 '18 at 01:59
  • @CBroe, you've pointed me in a direction where I found the Flex Items Formula: `content –> width –> flex-basis (limited by max|min-width)` – vter Apr 01 '18 at 02:58

1 Answers1

2

In order to understand the reason why the described behavior takes place, we should know how flex-basis and flex-grow actually work and how width of flex items is calculated.

Flex-grow

From flex-grow is weird. Or is it?

If we apply display: flex; to the parent element and don't change anything else, the child elements will be stacked horizontally, no matter what. If there isn't enough space, they will shrink in size. If on the other hand there is more than enough space, they won't grow, because Flexbox wants us to define how much they should grow. So rather than telling the browser how wide an element should be, flex-grow determines how the remaining space is distributed amongst the flex items and how big the share is each item receives.

Flex-basis

Width of a flex item is determined in the following order:

  1. content
  2. width
  3. flex-basis (limited by max|min-width)

From The Difference Between Width and Flex Basis

If no flex-basis is specified, then the flex-basis falls back to the item’s width property.

If no width is specified, then the flex-basis falls back to the computed width of the item’s contents.

vter
  • 1,881
  • 1
  • 20
  • 38
  • if you do a small search on the website you will also find the need answer for this as there is a lot of them well explained ... – Temani Afif Apr 01 '18 at 08:01