CSS Flexbox Layout
Flexbox lays out items along a single axis and distributes space between them, which makes responsive rows and columns simple.
- Flexbox
What flexbox solves
Before flexbox, centring a box vertically or distributing space evenly required floats and hacks. Flexbox makes both trivial.
The container
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}Key container properties
| Property | Purpose |
|---|---|
| flex-direction | Sets the main axis: row or column |
| justify-content | Aligns items along the main axis |
| align-items | Aligns items along the cross axis |
| flex-wrap | Allows items to move onto a new line |
| gap | Space between items |
Key item properties
.sidebar { flex: 0 0 260px; }
.content { flex: 1 1 auto; min-width: 0; }flex is shorthand for flex-grow, flex-shrink and flex-basis.
A responsive pattern
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 280px;
}Each card wants 280px, grows to fill the row and wraps when there is not enough space, with no media query required.
Conclusion
Reach for flexbox when laying out one dimension, and CSS grid when you need rows and columns at the same time.