Learn flexbox by pushing things around
Flexbox is easy to misread from a spec and easy to grasp once you drag a slider. This playground gives you a live canvas. Set the container: direction, wrap, justify, align and gap. Then set each item: grow, shrink, basis, order and self alignment. Property tips show beside the preview.
When the layout looks right, copy the CSS.
The two axes
Everything in flexbox depends on the main axis and the cross axis. justify-content works along the main axis. align-items works across it. Change flex-direction to column and they swap roles. That swap trips up almost everyone at first.
What flex: 1 means
It's shorthand for flex: 1 1 0. Grow by one share, shrink by one share, start from zero width. Items with flex: 1 share space equally, no matter their content.
Items won't shrink below their content by default. Add min-width: 0 to let long text or images shrink.
Gap beats margins
gap adds space between items only, not at the outer edges. With margins you end up fighting the first and last item. Gap is cleaner and works in flexbox now in all current browsers.
Flexbox or Grid
Use flexbox for one-dimensional layouts: a navbar, a button row, a card footer. Use grid for rows and columns together. Nest them freely. Flex containers can sit inside flex containers without trouble.
Everything you try stays in your browser.
Main axis and cross axis
Flexbox confuses people until they learn one idea. There's a main axis and a cross axis. With flex-direction row, the main axis runs left to right, so justify-content spreads items horizontally and align-items works vertically. Switch to column and the axes swap.
Once you know which way each axis points, the properties stop feeling random. Justify lines items up along the main axis. Align-items does the same along the cross axis. Gap adds space between items without margin tricks.
Use the playground to flip direction and watch the property tips update.
Grow, shrink and basis
Flex-grow says how much of the leftover space an item takes. Flex-shrink says how much it gives up when space is short. Flex-basis is the starting size. A common shorthand, flex: 1, means grow equally and start from zero.
Cards in a row, a sidebar next to content, a toolbar with one item pushed right using auto margin: all of these are a few lines of flexbox.
Remember min-width. A flex item won't shrink below its content by default, which is why long words or images sometimes break layouts.
- Use gap instead of margins between items
- Wrap when items shouldn't squeeze too small
- Set min-width: 0 on text items that need to shrink
- Reach for Grid when you need rows and columns