CSS Flexbox: The Complete Guide
CSS Flexbox: The Complete Guide
Flexbox is the most important CSS layout system to master. It handles one-dimensional layouts — either a row or a column — with elegant alignment controls.
The Basics
Apply display: flex to a container and its direct children become flex items:
.container {
display: flex;
}
Main Axis vs Cross Axis
Flexbox operates on two axes. The main axis follows flex-direction (default: row → horizontal). The cross axis is perpendicular.
Container Properties
flex-direction
Controls the main axis direction: row, row-reverse, column, column-reverse.
justify-content
Aligns items along the main axis: flex-start, center, flex-end, space-between, space-around, space-evenly.
align-items
Aligns items along the cross axis: stretch, flex-start, center, flex-end, baseline.
flex-wrap
By default items won't wrap. Set flex-wrap: wrap to allow multi-line layouts.
gap
Modern flexbox supports gap for consistent spacing between items:
.container {
display: flex;
gap: 1rem;
}
Item Properties
flex-grow
How much an item should grow relative to siblings. Default is 0 (don't grow).
flex-shrink
How much an item should shrink when there's not enough space. Default is 1.
flex-basis
The initial size before growing/shrinking. Often used as flex: 1 shorthand which sets flex-grow: 1; flex-shrink: 1; flex-basis: 0%.
align-self
Override the container's align-items for a single item.
Common Patterns
Centering
.container {
display: flex;
justify-content: center;
align-items: center;
}
Sticky Footer
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }
Navigation Bar
nav {
display: flex;
justify-content: space-between;
align-items: center;
}
Try It Live
Use our Flexbox Playground tool to experiment with all these properties visually. Adjust container and item settings and see the CSS output in real time.
Conclusion
Flexbox handles 90% of layout needs. Master the container properties (justify-content, align-items, flex-wrap, gap) and the flex shorthand, and you'll build layouts faster than ever.