Understanding Flexbox Alignment, Visually
justify-content or align-items? Main axis or cross axis? If you still guess which property to use, this interactive guide will fix that for good.
Here's a confession: for years, every time I needed to center something with Flexbox, I'd try justify-content, see that it did the wrong thing, and switch to align-items. It worked, but I didn't really understand why.
The secret is that Flexbox alignment isn't about horizontal and vertical. It's about axes.
The primary axis and the cross axis
Every flex container has two axes:
- The primary axis (often called the main axis) runs in the direction set by
flex-direction. With the defaultrow, it goes left to right. - The cross axis is perpendicular to it.
And the two properties map neatly onto them:
justify-contentdistributes items along the primary axis.align-itemspositions items along the cross axis.
That's the whole mental model. When you flip flex-direction to column, the axes rotate, and so do the effects of both properties. Try it:
.container {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: stretch;
}Why "justify" and "align" behave differently
You might notice that justify-content has options like space-between, while align-items has stretch and baseline. That's because they solve different problems.
Along the primary axis, items are laid out as a group. They sit side by side, so the question is how to distribute the leftover space between them.
Along the cross axis, each item is positioned individually. There's no "between" to worry about. Each item just decides where it sits in its own lane, which is why you can override it per item:
.special-item {
align-self: flex-end;
}Perfect centering, explained
So the classic centering snippet makes complete sense now:
.center {
display: flex;
justify-content: center; /* primary axis */
align-items: center; /* cross axis */
}We center the group along the primary axis, then center each item along the cross axis. No guessing required.
A quick cheat sheet
- Decide which way your items flow. That's
flex-direction, and it defines the primary axis. - Use
justify-contentto distribute items along that flow. - Use
align-itemsto position them in the other direction. - Reach for
align-selfor auto margins to break the rules for a single item.
Once you start thinking in axes, Flexbox stops being a guessing game.
… likes
Enjoyed it? Tap the heart (up to 10 times!)
Want to know when I publish something new?
I send a short email when there's a new article or project, usually a couple of times a month. No spam, and you can unsubscribe whenever you like.