Flexbox
1D layout with flex container and items
Skills taught: css.flexbox, css.flex-container, css.flex-items
Container properties
.container {
display: flex; /* activate flexbox */
flex-direction: row; /* row | row-reverse | column | column-reverse */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
/* Main axis (row direction by default) */
justify-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
/* Cross axis (column direction by default) */
align-items: stretch; /* stretch | flex-start | flex-end | center | baseline */
/* Space between items */
gap: 16px; /* row-gap and column-gap combined */
gap: 12px 24px; /* row-gap column-gap */
}
Item properties
.item {
/* flex shorthand: grow shrink basis */
flex: 1; /* flex: 1 1 0 — fill available space equally */
flex: auto; /* flex: 1 1 auto — grow/shrink from intrinsic size */
flex: none; /* flex: 0 0 auto — fixed size, no grow/shrink */
flex: 0 0 200px; /* fixed 200px, no grow/shrink */
/* Override cross-axis alignment for one item */
align-self: center;
/* Change visual order (don't use for logical order) */
order: 2;
}
Common flex patterns
/* Perfect horizontal + vertical centering */
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Navigation bar — logo left, links right */
.navbar {
display: flex;
align-items: center;
gap: 16px;
}
.navbar .spacer { flex: 1; } /* pushes everything after it to the right */
/* Equal-width card row that wraps */
.cards {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card {
flex: 1 1 280px; /* grow/shrink but never narrower than 280px */
}
Tip: Use gap instead of margins between flex items. Gap only applies between items (not to the outer edges), so you avoid the old 'first/last child margin' hack.
Frequently Asked Questions
What is the difference between justify-content and align-items?
justify-content distributes space along the MAIN axis (horizontal in row direction). align-items aligns items along the CROSS axis (vertical in row direction). Both axes flip if flex-direction: column.
When should I use flex: 1 vs flex: auto?
flex: 1 (grow from 0) distributes space equally regardless of content size. flex: auto (grow from intrinsic size) starts from each item's natural width — so larger content gets proportionally more space.
What is flex-wrap and why use it?
By default flex items all stay on one line and may shrink to fit. flex-wrap: wrap allows items to move to a new row when they would overflow — creating a responsive card grid without media queries.