Main axis and cross axis
Once you can name the two axes, every flexbox property starts making sense.
Most flexbox confusion vanishes the moment you stop thinking about horizontal and vertical. Flex containers don't care about the page. They have two axes of their own — a main axis and a cross axis — and which one is which depends entirely on a single property.
The main axis
The main axis is whichever direction your flex items lay out along. By default that's row: items flow left to right, and the main axis runs horizontally. Set flex-direction: column and the main axis rotates 90 degrees — items now flow top to bottom.
.gallery {
display: flex;
flex-direction: row; /* main axis = horizontal */
justify-content: space-between; /* aligns ON the main axis */
align-items: center; /* aligns ON the cross axis */
}Two properties control alignment: justify-content works along the main axis, and align-items works along the cross axis. The names will keep tripping you up unless you tie them to the axes, not to horizontal and vertical.
When you switch flex-direction to column, justify-content now controls vertical placement — the property didn't change, the axis did.
The cross axis
The cross axis is the perpendicular one. If main runs horizontally, cross runs vertically — and vice versa. align-items moves items along the cross axis as a group; align-self overrides it for a single item.
Flipping the direction
This is the part that earns flexbox its name. You can change which way is "main" without rewriting any of your alignment rules — they all keep referring to "main" and "cross" abstractly.
Tweak the controls above. Notice that when you switch from row to column, the same justify-content value now moves things vertically. The properties haven't changed; the axis they refer to has.
flex-direction: row-reverse reverses the main axis but not the cross axis. Items still align top-to-bottom by default — they just flow right-to-left.
Try it yourself
Before moving on, test the mental model: