Topic 06 / 14
Flexbox — One-Dimensional Layout
The Mental Model
Set display: flex on a container and its children line up along a main axis. You control distribution along that axis (justify-content) and alignment on the cross axis (align-items):
.row {
display: flex;
flex-direction: row; /* main axis → horizontal (default) */
justify-content: space-between; /* main-axis distribution */
align-items: center; /* cross-axis alignment */
gap: 1rem; /* space BETWEEN items — use this, not margins */
}justify-content (Main Axis)
justify-content: flex-start; /* default — packed at the start */
justify-content: center;
justify-content: flex-end;
justify-content: space-between; /* first/last flush, equal gaps between */
justify-content: space-around;
justify-content: space-evenly;align-items (Cross Axis)
align-items: stretch; /* default — children fill the height */
align-items: center; /* vertically centred (in a row) */
align-items: flex-start;
align-items: baseline; /* align text baselines — great for mixed font sizes */The Patterns You’ll Use Daily
/* 1. Perfect centering */
.hero {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* 2. Navbar: logo left, links right */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
/* 3. Push ONE item to the far end */
.nav .cta { margin-left: auto; } /* auto margin eats the free space */
/* 4. Media object: fixed icon + flexible text */
.media { display: flex; gap: 1rem; }
.media .icon { flex-shrink: 0; }
.media .body { flex: 1; }grow, shrink, basis
Per-child properties controlling how items share space:
.item {
flex-grow: 1; /* share of LEFTOVER space (0 = don't grow) */
flex-shrink: 1; /* may shrink below basis when tight (0 = never) */
flex-basis: 200px; /* starting size before grow/shrink */
}
/* the shorthand you'll actually write: */
.sidebar { flex: 0 0 280px; } /* fixed 280px, no grow, no shrink */
.content { flex: 1; } /* take everything else */Wrapping
.tags {
display: flex;
flex-wrap: wrap; /* overflowing items move to the next line */
gap: 0.5rem;
}Column Direction
.card {
display: flex;
flex-direction: column; /* main axis is now vertical */
}
.card .footer { margin-top: auto; } /* pin footer to the card bottom */That auto-margin footer trick makes equal-height cards with aligned buttons — a layout that was genuinely hard before flexbox.
Flexbox vs Grid: flexbox distributes items along one axis (navbars, toolbars, card internals); grid places items on two axes (page layouts, galleries). Next topic.