Chapter 3 introduced Flexbox; this chapter is the complete toolset. Flexbox lays out items along a single axis and excels at distributing space and aligning content — navbars, toolbars, card rows, centring. The one concept to truly internalise is the grow/shrink/basis model.
Main & cross axis
Everything in Flexbox is relative to two axes. flex-direction sets the main axis (row = horizontal, column = vertical); the cross axis is perpendicular. justify-content works along the main axis; align-items along the cross.
Container properties
| Property | Controls |
|---|---|
display: flex | Turn on flex layout |
flex-direction | row | row-reverse | column | column-reverse |
justify-content | Main-axis: start, center, space-between, space-around, space-evenly |
align-items | Cross-axis: stretch, center, start, end, baseline |
flex-wrap | nowrap | wrap — let items flow to new lines |
gap | Spacing between items |
align-content | Space between wrapped lines |
.row {display: flex;flex-wrap: wrap;gap: 16px;justify-content: space-between;align-items: center;}
Item properties
.item {flex: 1; /* grow to fill available space equally */align-self: flex-start; /* override the container's align-items for this item */order: 2; /* reorder visually without changing the HTML */}
grow / shrink / basis
The flex shorthand is flex: grow shrink basis:
- grow — how much of the leftover space this item takes (0 = don't grow).
- shrink — how much it shrinks when space is tight (0 = never shrink).
- basis — its starting size before growing/shrinking.
flex: 1; /* = 1 1 0 — share space equally */flex: 0 0 200px; /* fixed 200px, never grow or shrink (a sidebar) */flex: 2; /* takes twice the space of a flex: 1 sibling *//* Sidebar + fluid main content: */.sidebar { flex: 0 0 240px; }.main { flex: 1; }
Practice
Build a navbar: logo on the left, links on the right, vertically centred (hint: a spacer with flex: 1, or justify-content: space-between). Then a sidebar-plus-content layout with flex: 0 0 240px and flex: 1, and a wrapping tag row with gap.
Key takeaways
- 01flex-direction sets the main axis; justify-content aligns along it, align-items along the cross axis.
- 02Container: display:flex, flex-direction, justify-content, align-items, flex-wrap, gap.
- 03Item: flex (grow shrink basis), align-self, order.
- 04flex: 1 shares space equally; flex: 0 0 200px is a fixed, non-flexing size.
- 05Perfect centring is three lines: display:flex + align-items:center + justify-content:center.
