Episode 9 of 12
Axis
Deep dive into the main axis and cross axis — how flex-direction changes them and how alignment works on each.
Axis
Understanding the main axis and cross axis is the key to mastering Flexbox alignment. Every Flexbox property works along one of these two axes.
The Two Axes
| Axis | Default Direction | Controlled By |
|---|---|---|
| Main Axis | Horizontal (left → right) | justify-content |
| Cross Axis | Vertical (top → bottom) | align-items |
The cross axis is always perpendicular to the main axis.
How flex-direction Changes the Axes
| flex-direction | Main Axis | Cross Axis |
|---|---|---|
row (default) | Horizontal → | Vertical ↓ |
row-reverse | Horizontal ← | Vertical ↓ |
column | Vertical ↓ | Horizontal → |
column-reverse | Vertical ↑ | Horizontal → |
Visual: Row Direction
flex-direction: row (default)
Main Axis → → → → →
┌────────────────────────────────┐
│ ┌──────┐ ┌──────┐ ┌──────┐ │ ↓ Cross
│ │ Item │ │ Item │ │ Item │ │ ↓ Axis
│ │ 1 │ │ 2 │ │ 3 │ │ ↓
│ └──────┘ └──────┘ └──────┘ │
└────────────────────────────────┘
Visual: Column Direction
flex-direction: column
Cross Axis → → →
┌──────────────────┐
│ ┌────────────┐ │ ↓
│ │ Item 1 │ │ ↓ Main
│ └────────────┘ │ ↓ Axis
│ ┌────────────┐ │ ↓
│ │ Item 2 │ │ ↓
│ └────────────┘ │ ↓
│ ┌────────────┐ │ ↓
│ │ Item 3 │ │ ↓
│ └────────────┘ │
└──────────────────┘
justify-content — Main Axis
.container {
display: flex;
justify-content: center; /* Centers items along the MAIN axis */
}
/* In row: centers horizontally */
/* In column: centers vertically */
align-items — Cross Axis
.container {
display: flex;
align-items: center; /* Centers items along the CROSS axis */
}
/* In row: centers vertically */
/* In column: centers horizontally */
Perfect Centering
.container {
display: flex;
justify-content: center; /* Main axis: center */
align-items: center; /* Cross axis: center */
height: 100vh;
}
/* Items are perfectly centered both horizontally and vertically!
This is the simplest centering technique in CSS. */
The Mental Model
When you're confused about which property does what, ask these two questions:
- Which direction do items flow? → That's the main axis
- Which direction is perpendicular? → That's the cross axis
Then:
justify-content= main axis alignmentalign-items= cross axis alignment
Common Confusion
| Direction | Horizontal Centering | Vertical Centering |
|---|---|---|
flex-direction: row | justify-content: center | align-items: center |
flex-direction: column | align-items: center | justify-content: center |
The properties swap roles when you switch from row to column, because the axes swap!
Key Takeaways
- Flexbox has two axes: main (item flow direction) and cross (perpendicular)
flex-directiondetermines which axis is main and which is crossjustify-contentaligns along the main axisalign-itemsaligns along the cross axis- In
row: justify = horizontal, align = vertical - In
column: justify = vertical, align = horizontal - Both
center+center= perfect centering