Zero Greediness of Flex Elements in CSS
If flex-grow is zero for an element, that element will not participate in the distribution of available space. By default, greediness is zero, so elements without a specified flex-grow do not share available space with each other.
Let's do some calculations for example. Let's say we have three flex items, each with a width of 100px. Let's say the first item has no flex-grow (or it's 0), the second item has flex-grow equal to 2, and the third item has 3.
Let the parent width be 500px. Then the free space will be 200px, and for one unit of flex-grow there will be . It turns out that the width of the first element will remain 200px / 5 = 40px100px, since it does not participate in the distribution, the width of the second will be , and the width of the third is 100px + 2 * 40px
= 180px.
100px
+ 3 * 40px = 220px
Practical tasks
In all of the problems below, you'll be presented with some code with flex items that have a width and flex-grow. Given the code, calculate what sizes each item will have. Then run the code and check your calculations by measuring the actual widths of the items.
<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: 500px;
height: 200px;
border: 1px solid red;
}
.child {
height: 50px;
border: 1px solid green;
}
.elem1 {
width: 200px;
flex-grow: 0;
}
.elem2 {
width: 100px;
flex-grow: 1;
}
.elem3 {
width: 100px;
flex-grow: 1;
}
<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: 900px;
height: 200px;
border: 1px solid red;
}
.child {
height: 50px;
border: 1px solid green;
}
.elem1 {
width: 300px;
flex-grow: 0;
}
.elem2 {
width: 200px;
flex-grow: 3;
}
.elem3 {
width: 100px;
flex-grow: 2;
}
<div class="parent">
<div class="child elem1">1</div>
<div class="child elem2">2</div>
<div class="child elem3">3</div>
<div class="child elem4">4</div>
</div>
.parent {
display: flex;
width: 700px;
height: 200px;
border: 1px solid red;
}
.child {
height: 50px;
border: 1px solid green;
}
.elem1 {
width: 200px;
flex-grow: 0;
}
.elem2 {
width: 200px;
flex-grow: 0;
}
.elem3 {
width: 100px;
flex-grow: 1;
}
.elem4 {
width: 100px;
flex-grow: 1;
}