CSS offers you the ability to let flex items grow. By default, when you set the
justify-content
property to flex-start
, flex-end
, or center
, the flex items take up only as much room along the primary axis as they need for their content. This is admirably egalitarian, but it does often leave a bunch of empty space in the flex container. Interestingly, one of the meanings behind the “flex” in flexbox is that you can make one or more flex items grow to fill that empty space.You configure a flex item to grow by setting the flex-grow
property on the item:
<em>item</em> { flex-grow: <em>value</em>; }Here,
<em>value</em>
is a number greater than or equal to 0
. The default value is 0
, which tells the browser not to grow the flex items. That usually results in empty space in the flex container.For positive values of flex-grow
, there are three scenarios to consider:
- You assign a positive
flex-grow
value to just one flex item. The flex item grows until there is no more empty space in the flex container. For example, here's a rule that setsflex-grow
to1
for the element with classitem1
, and that item 1 will grow until there is no more empty space in the flex container:
.item1 { flex-grow: 1; }
- You assign the same positive
flex-grow
value to two or more flex items. The flex items grow equally until there is no more empty space in the flex container. For example, here's a rule that setsflex-grow
to1
for the elements with the classesitem1
,item2
, anditem3
, and items 1, 2, and 3 will grow until there is no more empty space in the flex container:
.item1, .item2, .item3 { flex-grow: 1; }
- You assign a different positive
flex-grow
value to two or more flex items. The flex items grow proportionally based on theflex-grow
values until there is no more empty space in the flex container. For example, if you give one item aflex-grow
value of1
, a second item aflex-grow
value of2
, and a third item aflex-grow
value of1
, then the proportion of the empty space given to each will be, respectively, 25 percent, 50 percent, and 25 percent. Here's some CSS that supplies these proportions to the elements with the classesitem1
,item2
, anditem3
:
.item1 { flex-grow: 1; } .item2 { flex-grow: 2; } .item3 { flex-grow: 1; }
To calculate what proportion of the flex container’s empty space is assigned to each flex item, add up the flex-grow
values, then divide the individual flex-grow
values by that total. For example, values of 1, 2, and 1 add up to 4, so the percentages are 25 percent (1/4), 50 percent (2/4), and 25 percent (1/4), respectively.