Flexbox is a one-dimensional layout system — it arranges items in a single row or column. It excels at distributing space, aligning items, and handling dynamic content sizes.
Enabling Flexbox
Apply display: flex to a container, and its direct children become flex items:
.row {
display: flex;
}By default, flex items sit in a row, don't wrap, and stretch to the container's height.
Direction and Wrapping
Control the flow direction and whether items wrap to new lines:
When flex-wrap: wrap is set, items that don't fit on one line move to the next. Without it, items shrink to fit.
Alignment
Flexbox has two axes: the main axis (direction of flow) and the cross axis (perpendicular). Alignment properties work along these axes.
justify-content (main axis)
space-between— equal gaps between items, no gap at edges.space-evenly— equal gaps everywhere, including edges.
align-items (cross axis)
stretch(default) — items fill the container's cross-axis size.baseline— items align by their text baselines (useful for mixed font sizes).
Individual item alignment
Override alignment for a single item with align-self:
Gap
The gap property adds space between flex items without affecting the edges:
This replaces the old technique of adding margins to items and removing the margin from the last one.
Flex Items: grow, shrink, basis
These three properties control how items share available space:
/* Shorthand: flex: grow shrink basis */
.item {
flex: 0 1 auto; /* default behavior */
}Common patterns:
Common Flexbox Patterns
Navigation bar
Card with footer pushed to bottom
Centering anything
Input with button
Order
Change visual order without changing HTML order. Use sparingly — it can confuse keyboard navigation:
.first-visually {
order: -1; /* moves before items with default order: 0 */
}