CSS Flexbox
Flexbox solves one problem extremely well: arranging items along a single axis while letting them share space, align, and wrap. Toolbars, navigation bars, card rows, button groups, and form field rows are all flexbox jobs. The layout becomes surprising the moment items need to shrink â because a flex item's minimum size defaults to its content, not to zero â and that single default causes most flexbox bugs in the wild.
This lesson builds a mental model you can reuse: axis first, then sizing, then alignment, then wrapping. Once those four clicks into place, flexbox stops being a bag of properties and becomes a small, predictable system.
The One-Line Mental Model
A flex container distributes free space along its main axis; everything else â alignment on the other axis, wrapping, ordering â hangs off that. You choose the main axis with flex-direction, decide how items grow or shrink with the flex shorthand, and control alignment with justify-content on the main axis and align-items on the cross axis.
What you will be able to do after this lesson: build a responsive navigation bar, center anything in two lines of CSS, make a toolbar that wraps gracefully on narrow screens, and diagnose why a flex child refuses to shrink.
Main Axis and Cross Axis
flex-direction: row (the default) makes the main axis horizontal; column rotates it. The names justify-content and align-items then flip meaning, which is the single biggest source of confusion:
| Property | Main axis (row) | Cross axis (row) |
|---|---|---|
justify-content | Horizontal distribution | â |
align-items | â | Vertical alignment |
align-self | â | Overrides align-items for one item |
align-content | â | Distributes wrapped lines as a group |
In a column container those roles swap: justify-content stacks children vertically, and align-items centers them horizontally.
Growing and Shrinking: The Three Ingredients
Every flex item carries three numbers, collapsed into the flex shorthand: flex-grow (share of leftover space), flex-shrink (share of overflow to absorb), and flex-basis (the starting size before free space is handed out).
| Shorthand | grow | shrink | basis | Typical use |
|---|---|---|---|---|
flex: 1 | 1 | 1 | 0% | Equal-width columns that fill the row |
flex: 2 | 2 | 1 | 0% | Twice the width of a flex: 1 sibling |
flex: none | 0 | 0 | auto | Fixed icon that never resizes |
flex: 0 1 auto | 0 | 1 | auto | Default: natural size, may shrink |
Setting flex-basis: 0 is the trick behind equal-height and equal-width card grids: with a zero basis, the only sizes left are the grown shares, so every item ends the same width regardless of its content.
.toolbar {
display: flex;
gap: 0.5rem;
align-items: center;
}
.toolbar .search {
flex: 1; /* takes all remaining space */
}
.toolbar button {
flex: none; /* buttons keep their natural width */
padding: 0.5rem 1rem;
}
.card-row {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
}
.card-row .card {
flex: 1 1 240px; /* grow, shrink, basis â wraps near 240px */
}
Alignment: Centering Without Rituals
Before flexbox, centering a block horizontally meant auto margins, negative margins, or table hacks. In a flex container it is one declaration on each axis: justify-content: center and align-items: center. Free space splits equally on both sides of the item, so it lands dead center.
justify-content offers several policies for leftover space. space-between pushes the first and last items to the edges â perfect for a logo left, actions right navigation bar. space-around gives every item equal half-space on both sides. space-evenly splits all gaps identically, which reads calmer in sparse rows.
Wrapping Rows and the gap Property
Flex items refuse to wrap by default, which is why a toolbar of many buttons overflows narrow screens. flex-wrap: wrap turns the container into a stack of lines; each line is laid out independently, and align-content controls how the lines share the vertical space. The gap property sets gutters between items and between wrapped lines without the double-margin collapse problems of old margin tricks.
min-width: auto â Why Items Refuse to Shrink
Here is the bug every flexbox developer meets once. A flex item's automatic minimum size is its content size: a long word, a wide table, or a white-space: nowrap button sets a floor that shrinking cannot cross. The row overflows the viewport, and horizontal scrolling appears from nowhere.
/* The bug: a long title forces the card wider than its column */
.card {
display: flex;
flex-direction: column;
}
.card h3 {
margin: 0;
}
/* The fix: let the item shrink below its content width */
.card h3,
.card p {
min-width: 0;
}
.card h3 {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Setting min-width: 0 removes the content floor so shrink can do its job; combining it with ellipsis truncation keeps the layout tidy. In column flex containers the same trap exists on the block axis as min-height: auto.
đĄDebugging overflow in flex layouts
When a flex row overflows its parent, inspect the children and look for an automatic minimum size. The quickest test is to add min-width: 0 (or min-height: 0 in columns) to the suspected child. If the overflow disappears, that item's content was setting the floor.
Flexbox vs Grid vs Flow Layout
Neither flexbox nor grid replaces the other; they answer different questions.
| Question | Best tool |
|---|---|
| Distribute items along one axis | Flexbox |
| Align items on two axes at once | Grid |
| Size tracks as fractions of the container | Grid with fr units |
| React to content size, intrinsic sizing | Flexbox |
| Full page scaffolding: header, sidebar, footer | Grid |
| Small component layout inside a card | Flexbox |
A practical rule of thumb: use grid when you can draw the layout as rows and columns before seeing the content; use flexbox when the content's size should drive the arrangement. Real pages mix both freely â a grid page shell containing flex components.
Order, Auto Margins, and Keyboard Pitfalls
The order property rearranges flex items visually without touching the DOM. It solves genuine problems: a mobile layout that wants sidebar content after the article while the reading order in the markup stays logical for desktop, or a contact panel that must appear last on phones but first on wide screens. Each item takes an integer; items with the default order of zero come first, then one, two, and so on.
The trap is that focus and screen-reader order always follow the DOM, never the visual arrangement. If a button appears on the left but the DOM places it last, keyboard users tab in a sequence that does not match what they see â a meaningful-sequence accessibility failure. Use order for visual regrouping of content whose reading order stays sane, and restructure the markup when the two genuinely diverge. Most teams touch the property once or twice per design and reach for grid placement when entire regions need reordering.
One more flexbox tool deserves a permanent spot in the kit: auto margins. An auto margin on a single child pushes it and everything after it to the far end, distributing free space on one side only â the classic logo-left, actions-right split without justify gymnastics. Auto margins absorb free space before flex-grow does, which also makes them the shortest way to center content inside a fixed-width flex child.
Common Mistakes
A flex child that will not shrink below its content width
Fix: Add min-width: 0 to the item, and truncate long text with ellipsis if needed.
Using justify-content to center on the wrong axis after switching flex-direction
Fix: Remember: justify works on the main axis, align on the cross axis.
Setting fixed widths on every card instead of flex-basis
Fix: Use flex: 1 1 240px so cards share space and wrap naturally.
Fighting wrapped-line spacing with margins on flex items
Fix: Use the gap property â it applies between items and between wrapped lines.
Key Takeaways
- Flexbox lays items out along one main axis; flex-direction chooses which axis that is.
- flex combines grow, shrink and basis â flex: 1 with basis 0 gives equal-width siblings.
- justify-content aligns on the main axis, align-items on the cross axis; they swap when direction flips.
- min-width: auto is why flex children refuse to shrink; min-width: 0 removes the content floor.
- flex-wrap plus gap replaces most hand-rolled toolbar and card-row layouts.
- Reach for Grid when the layout is two-dimensional; keep Flexbox for content-driven rows and columns.