CSS flex-grow: 1
In this article, we will see what will happen if we set the CSS “flex-grow” property to 1. The Flex grow property specifies what amount of space inside the flex container the item should take up if necessary. The flex grove factor is always relative to the size of the other items in the flex container. Let’s understand with an example:
Example:
HTML:
<div class="container">
<div class="item item-1">Item 1</div>
<div class="item item-2">Item 2</div>
<div class="item item-3">Item 3</div>
<div class="item item-4">Item 4</div>
<div class="item item-5">Item 5</div>
</div>
CSS:
#container{
border: 2px black solid;
display: flex; }
.item{
width: 50px;
height: 25px;
padding: 1px;
}
.item-1{
background-color: red;
}
.item-2{
background-color: green;
}
.item-3{
background-color: orange;
}
.item-4{
background-color: darkviolet;
}
.item-5{
background-color: yellow;
}
- In the above example, we have created a parent div and inside it we have created 5 child div items.
- Then we styled that like a row and 5 columns of items.
See the output, the flex items only take up space that is required to fit the content.
Output:So, there is a lot of extra space within the parent container. Sometimes though you don’t want the additional whitespace instead you want to flex items to grow to take up the remaining space. By default, all flex items have a flex-grow value of 0, which is why they don’t take up the available extra space.
- If we set the “flex-grow” property to 1 for item-5, item-5 will grow to take up all the remaining space in the container.
.item-5{ background-color: yellow; flex-grow: 1; }
If we set the “flex-grow” property to 1 for item-4 and item-5, the additional space will be evenly distributed between item-4 and 5. If there was a 100px available, item-4 would grow by an additional 50px and item-4 would grow by an additional 50px.
.item-4{
background-color: darkviolet;
flex-grow: 1;
}
.item-5{
background-color: yellow;
flex-grow: 1;
}
Conclusion
I hope you understand the concept of flex-grow property. We can also assign the all number as value for a flex-grow property but in this article, I covered only value 1.