Flexbox: One-Dimensional Layouts
Flexbox arranges items along a single line, row or column, and is the workhorse for navbars, toolbars, cards, and centering content.
.nav {
display: flex;
flex-direction: row; /* default: left to right */
justify-content: space-between; /* spacing along the main axis */
align-items: center; /* alignment along the cross axis */
gap: 16px;
}
The two axes
Flexbox thinks in terms of a main axis (the direction set by flex-direction) and a cross axis (perpendicular to it).
| Property | Controls | Common values |
|---|---|---|
justify-content | Spacing along the main axis | flex-start, center, space-between, space-around |
align-items | Alignment along the cross axis | flex-start, center, stretch |
flex-wrap | Whether items wrap to new lines | nowrap (default), wrap |
gap | Space between items | any length, e.g. 16px |
Sizing individual items
.sidebar { flex: 0 0 250px; } /* never grow, never shrink, fixed 250px */
.content { flex: 1; } /* grow to fill remaining space */
flex: grow shrink basis controls how a specific child behaves inside the flex container, flex: 1 is shorthand for "take an equal share of whatever space is left".
TIP
Centering something perfectly, both horizontally and vertically, used to be a running joke in CSS. With Flexbox it's three lines: display: flex; justify-content: center; align-items: center;.