Sub topic 2
Main axis and cross axis
This chapter assumes you know basic HTML, CSS selectors, the box model, and length units such as px and rem. It also assumes you can set display: flex on a container. Every other Flexbox property depends on the two axes described here.
The two axes
A flex container lays out its direct children, the flex items, along one line of travel. That line is the main axis. The cross axis runs perpendicular to it.
The main axis follows the container's flex-direction. The default is row, so the main axis runs horizontally and the cross axis runs vertically. With column, the two swap.
| flex-direction | Main axis | Cross axis |
|---|---|---|
| `row` (default) | left to right (in left-to-right languages) | top to bottom |
| `row-reverse` | right to left | top to bottom |
| `column` | top to bottom | left to right |
| `column-reverse` | bottom to top | left to right |
Why the axes matter
Two properties are tied to the axes, not to physical directions:
justify-contentdistributes items along the main axis.align-itemsaligns items along the cross axis.
Neither property means "horizontal" or "vertical". Their effect depends on the direction you chose.
.row-box {
display: flex;
flex-direction: row;
justify-content: center; /* centers horizontally */
align-items: center; /* centers vertically */
height: 200px;
}
.column-box {
display: flex;
flex-direction: column;
justify-content: center; /* centers vertically */
align-items: center; /* centers horizontally */
height: 200px;
}Both boxes produce a centered result for a single child. The properties are the same, but each one acts on a different physical direction.
A common error
A frequent mistake is switching flex-direction to column and leaving the alignment rules unchanged. The layout then seems to break. For example, a navigation bar that used justify-content: space-between to spread links across the width will now spread them down the height. If the container has no fixed height, the container is only as tall as its content, so there is no free space to distribute and the property appears to do nothing.
When a flex property seems to have no effect, ask two questions:
- Which direction is the main axis right now?
- Is there free space on the axis that this property controls?
Cross-axis size
By default, items stretch along the cross axis. In a row container, items grow to the height of the tallest item, unless they have an explicit height. This comes from the initial value of align-items, which is stretch. A later chapter covers the alignment values in detail.
Exercise
A container has display: flex; flex-direction: column; height: 300px; align-items: center;. Along which physical direction does align-items act, and where do the items end up horizontally?
Show answer
With column, the cross axis is horizontal, so align-items acts horizontally. The items are centered horizontally within the container, and they stack from top to bottom along the main axis.