You've seen how the children of a flex parent are by default jammed together at the start of the element. To change how the children are distributed along the main axis, you use the justify-content
property. Here the default distribution is made explicit using the value flex-start
:
Try setting justify-content
to these other possible values:
flex-end
center
All of these values keep the children in a clump. You also have the option to spread them out along the main axis. Try setting justify-content
to these spacing values:
space-between
space-around
space-evenly
Do you see the difference between these? Suppose there are N children in the flex parent. Any extra space in the flex parent will be divided up and distributed according to which spacing value you use:
space-between
, any extra space is broken into N - 1 chunks and inserted between the children.space-around
, any extra space is broken into N chunks and given to each of the children. Half is placed before the child and half after. This produces twice as much space between elements as at the beginning or end.space-evenly
, any extra space is broken into N + 1 chunks and inserted between the children and at the beginning and end.This same logic can be extended to the three earlier values:
flex-start
, any extra space is inserted after all the children.flex-end
, any extra space is inserted before all the children.center
, any extra space is divided into two. Half is placed before the first child and half after the last child.You could say that justify-content
lets you choose between six different schemes for arranging any extra space. Under this definition, the value of justify-content
has no bearing on the rendering if there is no extra space. You can test this by switching to a vertical layout, which causes the parent to snugly fit around its children:
Try changing justify-content
to its different values.
Suppose you have a flex parent with a vertical orientation, and you do want it to have extra space. You'll have to make sure its height is set accordingly. Here the parent is made to fill the viewport:
Notice how the content overflows off the bottom of the Preview panel? The flex parent is sized to match the viewport, but the body also has margin, which makes the content exceed the available space. Try fixing this by removing the margin from the body.
But what happens if the children do overflow the parent? Try filling up the flex parent with extra children and see what happens under various values of justify-content
.
You should see that justify-content
isn't just about where to put the spacing, as it impacts where elements are placed even when there is no extra space.