justify-content: distributing along the main axis
Most day-to-day layout tickets are placement tickets — "center this", "push these to opposite ends", "why is this misaligned" — and the two properties in this lesson close nearly all of them.
.row {
display: flex;
justify-content: space-between;
}| value | effect |
|---|---|
flex-start | pack items at the start (default) |
center | pack items in the middle |
flex-end | pack items at the end |
space-between | first and last touch the edges, equal gaps between |
space-around | equal space around every item |
For the cross axis, align-items: center is the value you will type most: it vertically centers the items of a row.
And gap: 16px adds fixed space between items, never at the edges. It is far cleaner than putting margins on the children.
The two famous recipes
Perfect centering: one child dead-center in its parent, the recipe behind almost every hero section (lesson 5-3: the full-screen opening banner):
.hero {
display: flex;
justify-content: center; /* main axis */
align-items: center; /* cross axis */
min-height: 100vh; /* vh from lesson 5-3 */
}The stretchy middle: flex-grow hands leftover space to an item. The classic header has a logo, a search box that fills whatever is left, then buttons:
.search {
flex-grow: 1;
}Items default to flex-grow: 0 and stay content-sized. Grow values split leftover space proportionally: an item with 2 gets twice as much extra as an item with 1.
Quiz
Which pair centers a child both horizontally and vertically in a flex row?
Your turn: the dashed container is 220px tall with three cards stuck in its top-left corner. In the CSS pane, add three declarations to .stage so the cards sit in the dead center as a group: display: flex, justify-content: center, and align-items: center. Then experiment: swap center for space-between and flex-end to watch each axis move independently.
Code exercise · javascript
Prove you understand space-between by computing it. Write spaceBetween(containerWidth, itemWidth, count) that returns the x position of each item's left edge: first item at 0, last item touching the right edge, leftover space split into equal gaps.