Course outline · 0% complete

0/30 lessons0%

Course overview →

The flex mental model: main and cross axis

lesson 6-1 · ~9 min · 18/30

Quiz

Warm-up from lesson 5-1: which box-model layer pushes *neighbors* away?

One line of CSS, a new layout world

Block elements stack vertically (lesson 5-2), so putting things side by side used to be painful. Flexbox fixes that:

.toolbar {
  display: flex;
}

The element with display: flex becomes a flex container, and its direct children become flex items that line up in a row. Two roles, two sets of properties:

  • Container properties decide how the group flows: flex-direction, justify-content, align-items, gap.
  • Item properties decide how one child behaves: flex-grow and friends.

Almost everything about flexbox follows from one idea, shown in the next figure: the main axis.

Main axis and cross axis

  • The main axis is the direction items flow: horizontal for flex-direction: row (the default), vertical for flex-direction: column.
  • The cross axis is the perpendicular one.

Every alignment property picks an axis:

  • justify-content positions items along the main axis.
  • align-items positions them along the cross axis.

Switch flex-direction to column and the axes swap, so justify-content suddenly moves things vertically. That is the whole trick: never memorize horizontal or vertical, always ask which axis.

main axis (row)crossjustify-content: flex-startjustify-content: centerjustify-content: space-between
Same three items, three justify-content values. All movement happens along the gold main axis.

Quiz

A container has flex-direction: column. Which property moves its items toward the vertical center?

The three cards stack vertically because divs are block elements. In the CSS pane, make .row a flex container with a 16px gap between items. Then try adding justify-content: center to see the group move.