Home > database >  How exactly does flex-basis work in combination with flex-grow?
How exactly does flex-basis work in combination with flex-grow?

Time:03-09

look at this simple example:

#main {
  width: 300px;
  height: 100px;
  border: 1px solid #c3c3c3;
  display: flex;
}

#main div:nth-of-type(1) {
  flex-grow: 1;
  flex-basis: 50%;
}

#main div:nth-of-type(2) {
  flex-grow: 1;
  flex-basis: 0;
}

#main div:nth-of-type(3) {
  flex-grow: 1;
  flex-basis: 0;
}
<h1>The flex-grow Property</h1>

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;"></div>
  <div style="background-color:khaki;"></div>
</div>

The result will be that first div will have 200px width, 2nd and 3rd div will have 50px and 50px width respectively.

From where does this 200px come from? If I'm telling the first div to grow 50% of its size, it should be 150px (because it had 100px initially without flex-basis). If I'm telling it to grow 50% of the parent's size, then it should be 250px. How does it compute to get 200px width?

Example Fiddle: first step

Step 2

Since each div has an equal flex-grow property, the remaining 150px will be divided equally between them, so 50px each.

The first div then becomes 150px 50px = 200px, and the second and third become 0px 50px = 50px.

second step

This is based on the concept of positive and negative free space which is used to determin flex item sizes.

  • Related