Articles /
Flexbox fundamentals
Flexbox is the workhorse of one-dimensional layout. Understand its mental model once and you will reach for it confidently every day.
Main axis vs. cross axis
Flexbox has two axes. The main axis follows flex-direction (default: row). The cross axis is perpendicular to it. Every alignment property maps to one of these two axes.
.row { display: flex; flex-direction: row; } /* → main axis horizontal */
.col { display: flex; flex-direction: column; } /* ↓ main axis vertical */
Wrapping and gap
By default flex items squeeze onto one line. Add flex-wrap: wrap so items flow to the next line, and use gap for consistent spacing.
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.tag-list span {
padding: 0.25em 0.75em;
background: oklch(92% 0.04 270);
border-radius: 999px;
}
gap replaced the old margin-hack technique. It works in Flexbox in all modern browsers since 2021.flex-grow, flex-shrink, flex-basis
The flex shorthand sets all three at once. The most common patterns are flex: 1 (grow to fill) and flex: none (stay at content size).
.sidebar { flex: 0 0 16rem; } /* fixed 16rem, no grow, no shrink */
.main { flex: 1; } /* takes remaining space */
.icon { flex: none; } /* intrinsic size only */
flex-grow— how much extra space this item gets (0 = none).flex-shrink— how much it shrinks when space is tight (1 = default).flex-basis— starting size before grow/shrink (default:auto).
Alignment
Use justify-content on the main axis, align-items on the cross axis, and align-self on individual items.
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem;
background: oklch(18% 0.02 260);
}
Common patterns
These everyday patterns rely on just a few flex properties.
/* push last item to the right (e.g., a logout button) */
.nav-item:last-child { margin-inline-start: auto; }
/* perfect centering */
.center { display: flex; align-items: center; justify-content: center; }
/* sticky footer: body is flex column, main grows */
body { display: flex; flex-direction: column; min-height: 100dvh; }
main { flex: 1; }
When to use Grid instead
Flexbox is one-dimensional — it excels at a single row or column. When you need to control rows and columns simultaneously, CSS Grid is the right tool.
- Nav bars, toolbars, tag lists — Flexbox.
- Card grids, page layouts, dashboard tiles — Grid.
- When items should wrap into equal-width columns — Grid with
auto-fill.