Flexbox
One-axis layout: justify, align, gap, flex: 1 and everyday recipes.
Updated
What Flexbox is
Flexbox is a layout system on a single axis: you arrange an element's children in a row or a column, and control the space between them and their alignment. You turn it on on the parent:
.toolbar { display: flex; }From that moment on, the direct children become flex items.
The two axes
flex-direction: row (default) |
flex-direction: column |
|
|---|---|---|
| Main axis | horizontal → | vertical ↓ |
| Cross axis | vertical | horizontal |
Everything is relative to the axes, not to "left/top":
justify-content— alignment on the main axis.align-items— alignment on the cross axis.
Properties on the parent
| Property | Common values | Effect |
|---|---|---|
flex-direction |
row, column |
the direction |
justify-content |
flex-start, center, space-between, flex-end |
distributes on the main axis |
align-items |
stretch (default), center, flex-start, baseline |
aligns on the cross axis |
gap |
1rem |
space between children |
flex-wrap |
nowrap (default), wrap |
move to the next row when they don't fit |
Properties on the children
.item { flex: 1; } /* share the remaining space equally */
.search { flex: 1; min-width: 0; } /* grows, but can also shrink */
.logo { flex-shrink: 0; } /* never shrinks */
.last { margin-left: auto; } /* pushes the element to the end */flex is shorthand for flex-grow flex-shrink flex-basis:
| Value | Means | When |
|---|---|---|
flex: 1 |
grows and shrinks, basis 0 | equal columns, an input that fills the row |
flex: none |
fixed size | icon, avatar, button |
flex: auto |
grows starting from the content size | tabs of different widths |
Everyday recipes
/* perfect centering */
.center { display: flex; justify-content: center; align-items: center; }
/* header: logo on the left, menu on the right */
.header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
/* card with a footer stuck to the bottom */
.card { display: flex; flex-direction: column; }
.card footer { margin-top: auto; }Flexbox or Grid?
| Flexbox | Grid |
|---|---|
| one dimension — row OR column | two dimensions — rows AND columns |
| the content dictates the size | the layout dictates the size |
| navbar, toolbar, buttons, centering | pages, galleries, dashboards, aligned forms |
You often combine them: grid for the page, flex inside the cards.
The classic mistake
Long text in a flex item that won't shrink: children have min-width: auto by default. The fix: min-width: 0 on the item (or overflow: hidden).
Summary
display: flexon the parent; the children line up on one axis.justify-content= main axis,align-items= cross axis.gapfor spacing,flex: 1to fill the space.