
Flexbox arranges the direct children of a container along a main axis and aligns them across a perpendicular cross axis. The axes follow the direction and writing mode of the layout.
1. Create a flex container
Use display: flex for a block-level container and display: inline-flex for an inline-level container. Its direct children become flex items.
.toolbar { display: flex; gap: .75rem; }2. Wrap flex items
nowrap keeps items on one line. wrap allows multiple lines, and wrap-reverse reverses how flex lines stack across the cross axis.
.toolbar { flex-wrap: wrap; }3. Distribute space along the main axis
justify-content supports values such as flex-start, flex-end, center, space-between, space-around, and space-evenly. It only distributes free space.
4. Align items across the cross axis
align-items supports stretch, flex-start, flex-end, center, and baseline. align-self overrides the default for an item. Use align-content to place multiple lines when there is extra cross-axis space.
5. Set the main axis
flex-direction can be row, row-reverse, column, or column-reverse. Reversing the visual direction does not reverse reading order or keyboard order.
6. Grow, shrink, and basis
flex-basis is the starting size, flex-grow is the share of positive free space, and flex-shrink helps distribute a shortage according to base sizes. The flex shorthand combines all three.
.card { flex: 1 1 16rem; min-width: 0; }7. Reorder only when appropriate
order affects visual placement. Keep the HTML order meaningful for readers and keyboard navigation.
8. Practice
Build a toolbar that wraps and a card row where items can grow. Try a long unbroken label, then use DevTools to compare the item’s basis, actual size, and minimum size.
| Task | Property |
|---|---|
| Choose direction | flex-direction |
| Permit multiple lines | flex-wrap |
| Distribute main-axis space | justify-content |
| Align items on cross axis | align-items |
| Set item flexibility | flex-grow, flex-shrink, flex-basis |
Original CodePen examples
- Open example 1
- Open example 2
- Open example 3
- Open example 4
- Open example 5
- Open example 6
- Open example 7
- Open example 8
- Open example 9
- Open example 10
- Open example 11
Visual references from the original lesson




