coding180 icon
Coding180
Flexbox - (flex-grow)

Flexbox - (flex-grow)

Home > Tutorials > CSS > CSS Flexbox


The flex-grow property is the first that we will see that is applied to the elements that are inside the container, that is, to the items.

This property stores an integer value and controls how large the item will grow to fill the space not used by other items.

The default value of theflex-grow property is (it does not have a unit of measure, since it indicates a growth factor)

Let's look at an example to understand this property. If we have three items, let's try to define the growth factor with the value 1 for the first item and leave the other two flex-grox with zero:

Initially, the flex-grow property of each item has a value of 0, and we can see that on the right all the space of the container not occupied by the flex boxes appears in black. Immediately that we change the value to 1 for the flex-grow of the first flex box, we verify that all that available space is monopolized by said box.

Let us now try to also have a 1 in the second box. We will verify that the available space is distributed between the first two flexible boxes.

A value other than one makes sense if we want that space to be distributed with another proportion, for example if we have a 2 in the first item and a 1 in the second item, then it means that the available space is distributed giving 2/3 parts for the first item and 1/3 part for the second item.

The flex-grow property cannot store a negative value.

Problem: Define a Flexbox with three items. Make the second item take up all the free space using the "flex-grow" property.

page1.html

<!DOCTYPE html>
<html>
<head>
  <title>Problem</title>
  <meta charset="UTF-8">
  <link rel="StyleSheet" href="styles.css" type="text/css">
</head>
<body>
  <div id="container1">
    <div id="item1">item 1</div>
    <div id="item2">item 2</div>
    <div id="item3">item 3</div>
  </div>
</body>
</html>

styles.css

#container1{
  display: flex;
  background-color: #000;  
  height: 300px;
  color:white;
  font-size:2rem;
}

#item1 {  
  background-color: #0078A6;
}
#item2 {
  flex-grow: 1;
  background-color: #0084B6;
}
#item3 {
  background-color: #008CC1;
}

Only the #item2 element is initialized by the flex-grow property:

flex-grow: 1;

The other two items default to 0 in the flex-grow property.

photo


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel