justify-content vs align-items: which axis is which

· Tags: flexbox, layout

If you have ever written justify-content: center hoping to vertically center a thing and watched it sit stubbornly on the left, you have met the axis problem. The fix is not memorising more property names. It is keeping two words straight: main and cross.

The axis is set by flex-direction

A flex container has one main axis and one cross axis, perpendicular to each other. flex-direction: row (the default) puts the main axis horizontal; flex-direction: column puts it vertical. The CSS Flexible Box Layout Module Level 1 spec (W3C Candidate Recommendation, 2017) defines the axes in exactly those terms — everything else is derived.

justify-* is always main; align-* is always cross

That is the whole rule. justify-content distributes space along the main axis. align-items positions items on the cross axis. Change flex-direction and the direction of those properties flips, but the binding to main-vs-cross never does. MDN's "Basic concepts of flexbox" page is the canonical reference; Rachel Andrew's The New CSS Layout (A Book Apart, 2017) walks through the same distinction with diagrams.

Why vertical centering "used to be hard"

Before flexbox, there was no CSS property that targeted the cross axis of a block-level box. Vertical centering required either a table cell, a negative-margin hack, or absolute positioning with transform: translateY(-50%). With flexbox it is two declarations on the parent: display: flex; align-items: center. Chris Coyier's CSS-Tricks "Complete Guide to Flexbox" (first published 2013, continuously updated) is the most-linked reference for this and worth bookmarking.

Content vs items vs self

justify-content and align-content distribute extra space in the container. align-items sets the default cross-axis alignment for all items. align-self overrides it on a single item. The naming is consistent once you notice the pattern: -content acts on the group, -items sets the group default, -self overrides per item.

Related

Get FlexFrog on the App Store