Different element widths and flex block compression in CSS
Now let our elements have different widths. In this case, the split-off piece will be proportional to the width of this element and will be calculated using the following formula: neg. free space * (element width / sum of all element widths).
Let's say we have 4 elements. Let's say the width of the first element is 400px, the width of the rest of the elements is 200px, and the width of the parent is 900px.
The total width of the elements is:
400px + 3 * 200px = 1000px
Then the negative free space will be:
1000px - 900px = 100px
Let's find how much of the first element will be pinched off:
100px * (400px / 1000px) = 40px
That is, its width will be equal to:
400px - 40px = 360px
Let's find how much of each of the remaining elements:
100px * (200px / 1000px) = 20px
That is, the width of these elements will be equal to:
200px - 20px = 180px
Implement the described blocks and check by measurement that the width of the elements will actually be equal to the one we calculated.
Calculate the width of the blocks and then check your calculations by measuring:
<div class="parent">
<div class="child elem1">1</div>
<div class="child elem2">2</div>
<div class="child elem3">3</div>
</div>
.parent {
display: flex;
width: 300px;
height: 200px;
border: 1px solid red;
}
.child {
height: 50px;
border: 1px solid green;
}
.elem1 {
width: 300px;
}
.elem2 {
width: 100px;
}
.elem3 {
width: 100px;
}