Flexbox
Flexbox lays out items in one direction, a row or a column, and makes aligning, spacing and distributing them easy. Navigation bars, button groups, cards in a row and centring things are all flexbox jobs.
Turning it on
Set display: flex on the container. Its direct children become flex items.
gap adds space between items. It's much better than margins.
The two axes
- Main axis: the direction items flow in (
flex-direction: row= horizontal,column= vertical). - Cross axis: perpendicular to it.
| Property (on the container) | Aligns along | Common values |
|---|---|---|
justify-content |
Main axis | flex-start, center, flex-end, space-between, space-around, space-evenly |
align-items |
Cross axis | stretch (default), flex-start, center, flex-end, baseline |
Playground
Change the values and watch the boxes move:
Perfect centring
The most famous CSS problem, solved in three lines:
A real navbar
margin-left: auto on a flex item soaks up all the free space. It's a very handy trick.
Growing, shrinking and wrapping
The flex property on items controls how they share space: flex: <grow> <shrink> <basis>.
flex-wrap: wrap lets items move onto new lines. It's the basis of responsive card rows:
Item-level overrides
align-self: overridealign-itemsfor one item.order: change the visual order (but the screen-reader and tab order don't change, so use it sparingly).flex-shrink: 0: stop an item, such as an icon or avatar, from being squashed.
Practice
Build a "media object": an avatar image on the left that never shrinks, and text on the right that fills the remaining space, vertically centred. Then put three of them in a column with 16px gaps.
1.In a flex-direction: row container, which property centres items horizontally?
2.Which item property makes an item take up all the remaining space?