0

In following example .flex2 has 2 childs.

  • 1 child - width: 300px
  • 2 child - width: 100%

.b{
  height: 50px;
}

.flex2{
  margin-top: 20px;
  display: flex;
  
  .box{
    background-color: blue;
    width: 300px;
  }
  
  .box1{
    background-color: purple;
    width: 100%;
  }
}
<div class="flex2">
  <div class="box b">
    box
  </div>
  
  <div class="box1 b">
    box 1
  </div>
</div>

Why width: 100% (2 child) compresses a bit 1 child block with width 300px?

I do understand that % of width depends on the parents block width, but still dont get it.

So, can someone explain to me, why 100% shifts block only a little bit?

asdasd
  • 63
  • 1
  • 8

1 Answers1

0

The flex containers have flex-shrink: 1 by default which makes them shrinkable proportionally to fit into the parent container. If you want to keep the first child at 300px without shrinking, you can add flex-shrink: 0 to first child styling. Hope this helps

guvvanch
  • 11
  • 2
  • Still don't get it. Why it shrinks only by few pixels then, and not by all 100% of parents available space? – asdasd May 04 '23 at 21:25
  • @asdasd you have to read the full shrink algorithm to understand – Temani Afif May 04 '23 at 21:26
  • 1
    @asdasd if you calculate the percentage of shrinkage for both boxes, you will see that they shrink proportionally. For example, if the parent container has total width of 600px, you should have 1.child with 200px and 2.child with 400px. That way, they each have shrunk 33%. First child from 300px to 200px, and second child from 600px (100%= 600px in this case) to 400px. I tested your code in the playground and that is the case. Hope this helps – guvvanch May 04 '23 at 21:37
  • here's the formula for A & B inside P (parent) : X = widthP / (widthA + widthB) ; newA = widthA * X; //widthA after shrink newB = widthB*X; //widthB after shrink – AJ Zack May 04 '23 at 22:13