Sub topic 9
Sharing extra space with flex-grow
This chapter assumes you can write a CSS rule, know the box model, and have already made a flex container with display: flex. You should also know what the main axis is and what flex-basis does.
What flex-grow does
After the browser places each item at its flex-basis size, the container may have free space left on the main axis. flex-grow decides how that leftover space is divided among the items.
The value is a unitless, non-negative number. The default is 0, which means the item does not grow. An item with flex-grow: 1 takes a share of the free space.
How the space is divided
The browser adds up all the flex-grow values on the line. Each item receives free space in proportion to its own value.
.row {
display: flex;
width: 600px;
}
.row .a { flex-basis: 100px; flex-grow: 1; }
.row .b { flex-basis: 100px; flex-grow: 2; }
.row .c { flex-basis: 100px; flex-grow: 0; }The bases total 300px, so 300px is free. The grow values total 3. Item a gets 100px (1/3), and item b gets 200px (2/3). Item c gets nothing.
The final widths are:
| Item | Basis | Extra space | Final width |
|---|---|---|---|
| a | 100px | 100px | 200px |
| b | 100px | 200px | 300px |
| c | 100px | 0px | 100px |
Grow values are shares, not sizes
flex-grow: 2 does not make an item twice as wide as one with flex-grow: 1. It gets twice as much of the free space. Final width is basis plus share, so items with different bases stay different even with equal grow values.
If you want equal widths regardless of content, set the basis to 0 as well. Then all the space is free, and equal grow values split it evenly.
.equal {
display: flex;
}
.equal > * {
flex-grow: 1;
flex-basis: 0;
}When there is little free space
If the free space is less than the sum of the grow values, the fractions still apply. For a total grow of 0.5, the items take only half of the free space. The rest stays empty.
.partial {
display: flex;
width: 400px;
}
.partial .x {
flex-basis: 100px;
flex-grow: 0.5;
}Here 300px is free, and the single item takes 150px of it. The item ends up 250px wide.
Common mistakes
- Expecting growth when there is no free space. If the items already fill or overflow the line,
flex-growhas nothing to distribute. - Forgetting that the basis counts. Content-sized items with equal
flex-growend up unequal unless you setflex-basis: 0. - Using
flex-growon the container. It applies to flex items only.
Exercise
A flex container is 500px wide and holds two items. Item one has flex-basis: 100px and flex-grow: 1. Item two has flex-basis: 200px and flex-grow: 3. What is the final width of each item?
Show answer
The free space is 500 - 300 = 200px. The grow total is 4. Item one gets 50px, so it is 150px wide. Item two gets 150px, so it is 350px wide.