A Worked Example of `flex-grow` (CSS)

Consider the following code snippet. Each div has a different flex-grow factor set. Given the flex-container’s width, and the flex-item’s initial width, what do you expect the final width of the flex-item to be?

<div class="flex">
	<div class="flex-grow-1">flex-grow-1</div>
	<div class="flex-grow-2">flex-grow-2</div>
	<div class="flex-grow-3">flex-grow-3</div>
	<div class="flex-grow-4">flex-grow-4</div>
</div>
div.flex {
	width: 1500px;
	display: flex;  
}

div > div {
	border: 1px solid red;	
  	width: 100px;
}

div.flex-grow-1 {
	flex-grow: 1;
}

div.flex-grow-2 {
	flex-grow: 2;
}

div.flex-grow-3 {
	flex-grow: 3;
}

div.flex-grow-4 {
	flex-grow: 4;
}

What will the widths of the items be?

  1. Add up the total growth factors: 1 + 2 + 3 + 4 = 10
  2. Get the total width: 1500px
  3. Get the size of the items: 100px
  4. We have 1500px - (4 * 100px) = 1100px space to distribute.
  5. Now let’s look at flex-grow-4: it has a grow factor of: 4.
  6. Therefore we can expect it to be: 4 / 10 * 1100 = 440px and let’s add that up to it’s initial size: 440px + 100px = 540px should be the total size.

But the calculated value in firefox returns: 536.8. This is due to us adding a border to all the divs. In other words: we must add the padding and margins, and calculate the space remaining. In other words, the space remaining is actually less than 1100px due to the adding of 1px borders among some of the div elements.

Test it out here:

See the Pen css - flex-grow by Ben Koshy (@Ben-Koshy-the-animator) on CodePen.

A similar calculation applies to all the other divs.

The same concept applies to flex-shrink except in the reverse.

Written on January 4, 2025