The definitive Flexbox reference — every container and item property, the flex shorthand fully decoded, five essential patterns, and common pitfalls.
Flexbox is the most widely used CSS layout module for component-level design. Every Flexbox decision is made relative to two axes. The main axis runs in the direction set by flex-direction. The cross axis is perpendicular. Properties prefixed with justify- work on the main axis. Properties prefixed with align- work on the cross axis. Memorise this — it makes every other Flexbox property immediately logical.
.container {
display: flex;
flex-direction: row; /* main: left→right (default) */
flex-direction: column; /* main: top→bottom */
/* When column: justify-content = vertical,
align-items = horizontal */
}
justify-content: flex-start; /* pack to start */
justify-content: flex-end; /* pack to end */
justify-content: center; /* centre */
justify-content: space-between; /* edges at ends, equal gaps between */
justify-content: space-around; /* equal space on each side of item */
justify-content: space-evenly; /* equal space everywhere incl. edges */
align-items: stretch; /* fill cross-axis (default) */
align-items: center; /* centre on cross axis */
align-items: flex-start; /* align to cross-axis start */
align-items: baseline; /* align on first text baseline */
/* Per-item override */
.special { align-self: flex-end; }
/* flex: grow shrink basis */
.item { flex: 1; } /* 1 1 0% — grows, shrinks from zero */
.item { flex: auto; } /* 1 1 auto — grows, shrinks from natural size */
.item { flex: none; } /* 0 0 auto — fixed natural size */
/* Sidebar + main layout */
.sidebar { flex: 0 0 260px; } /* rigid 260px */
.main { flex: 1; } /* takes remaining space */
.container {
flex-wrap: wrap; /* items wrap to new lines */
gap: 24px; /* consistent spacing, replaces margin hacks */
gap: 16px 24px; /* row-gap col-gap */
}
/* 1. Perfect centring */
.centre { display:flex; align-items:center; justify-content:center; min-height:100vh; }
/* 2. Sticky footer */
body { display:flex; flex-direction:column; min-height:100vh; }
main { flex:1; }
/* 3. Card with pinned CTA */
.card { display:flex; flex-direction:column; }
.card-content { flex:1; }
.card-cta { margin-top:auto; }
/* 4. Nav: logo left, links right */
nav { display:flex; align-items:center; gap:8px; }
.nav-brand { margin-right:auto; }
/* 5. Equal-height cards in a row */
.row { display:flex; gap:20px; }
.card { flex:1; }
Use Flexbox for one-dimensional component internals. Use Grid for two-dimensional layouts where rows and columns must align simultaneously. Most UIs use both.
Once you internalise the main/cross axis mental model, every Flexbox property becomes immediately logical and you stop fighting the layout engine and start directing it.