Home > Net >  How flex-srink is calculated automatically?
How flex-srink is calculated automatically?

Time:10-08

I have this HTML

 <div class="parent">
        <div class="child one">child</div>
        <div class="child two">This is some longer content sdsds ds dssdsdsd sds dsdsdsdsdsd sd sd sds sdsdsdsds sdsdsd
            sd sd sd sd sdsdsdsdsds sdsdsdsd sds dsdsdsds sdsdsdsdsdsdsd</div>
        <div class="child three">child</div>
       
</div>

AND CSS

.parent {
    background-color: #001f3f;  
    display: flex;
    width: 900px;
    background-color: rgb(85, 78, 78);
}

.child {
    background-color: #0074d9;
    color: white;
    flex-basis: 400px;
    text-align: center;
}

as you can see i have setted 400px of each child and my parent has 900px width. Because i have 3 x 400px = 1200px, then my items are automatically shrinked in its container - because flex-shrink:1 is the default option.

But when i add for example on my third item

.three {
    flex-shrink: 2;
}

then my first and second item has width of 325px and my third items has width of 250px. So together 900px.

I can't understand how this calcultions are maked based on the number 2 in the flex-shrink property.

For example by flex-grow if we have two items with the width of 200px, our parent has width 800px the REMAINING SPACE IS 400PX.

That 400px is divided across this two items.

How about the flex-shrink in my example ?

But when i add flex-shrink for example to th third item

CodePudding user response:

This is the formula:

new width = width - (shrink space x shrink ratio)

To calculate shrink space: 
shrunk space = total children widths - parent width = 1200 -900 = 300

To calculate shrink ratio:
shrink ratio (For third div) = (width x flex shrink) / Σ(width x flex shrink) = 400*2/(400*1   400*1   400*2) = 0.50  
shrink ratio (For first and second div) = (width x flex shrink) / Σ(width x flex shrink) = 400*1/(400*1   400*1   400*2) = 0.25

So your new width will become :
new width(For third div) = 400 - (300 x 0.50) = 250
new width(For first/second div) = 400 - (300 x 0.25) = 325
  • Related