Expansion

When you run a desktop application, what happens to the widgets as you enlarge the window? They often get bigger, expanding to fill the void that is opened up. This same effect can be achieved in web applications using Flexbox.

With the Flexbox examples you've seen so far, any extra space on the main axis of a flex parent is distributed between or around the flex children. The justify-content property determines how this space is allotted. If you instead want the extra space to be given to the child elements, then you must set the flex-grow property. Unlike all the previous Flexbox properties you've seen, flex-grow is assigned on the children themselves.

Before you see flex-grow in action, consider this flex parent that contains just two children of class tile:

html
css
preview

Notice how distinct colors have been assigned to the tiles. Instead of giving each a unique id and targeting them using an id selector, the nth-child pseudoselector is used. This pseudoselector expects the child's 1-based index as a parameter. The selector .tile:nth-child(1) targets any element that has class tile and is the first child within its parent.

An element's flex-grow value is a number that represents its share of the extra space. The weight of an element only has meaning when you consider it relative to the weights of its siblings. Suppose the first tile has weight 2 and the second weight 1. The weights sum to 3. The first tile will get 2/3 of any extra space, and the second tile 1/3:

html
css
preview

Try resizing the window. Observe how both tiles grow as the window gets larger. The first tile continues to get twice as much of the extra space.

Notice also how all the parent no longer owns the extra space. The value of justify-content is effectively ignored when the children expand.

What do you suppose will happen when you give the first tile a weight of 0 and the second a weight of 1?

html
css
preview

Try resizing the window.

The weights sum to 1. The first gets 0/1 of any extra space, and the second 1/1. Only the second tile expands.

What do you suppose will happen when both tiles have a weight of 20?

html
css
preview

Try resizing the window.

The weights sum to 40. The first gets 20/40 of any extra space, and so does the second. Both get half of any extra space. In this case, flex-grow should have been set to 1 to prevent confusion.

The examples above consider only two children. Expansion can be applied to any number of children. Try adding a third tile and setting its background-color and flex-grow properties.