CSS Flexbox
How Flexbox Works
Flexbox is a layout model designed for distributing space along a single axis. Set display: flex on a container and its direct children become flex items. The container controls the direction, alignment, and spacing. Each item can grow, shrink, or stay fixed.
The key mental model: flex has a main axis (the direction items flow) and a cross axis (perpendicular to it). By default the main axis is horizontal (left to right), but flex-direction: column flips it to vertical.
Basic Flex Container
That is all you need. Items sit in a row with equal spacing. No floats, no clearfixes.
justify-content — Main Axis Alignment
Controls how items distribute along the main axis.
flex-start (default)
center
space-between
align-items — Cross Axis Alignment
All items vertically centered regardless of their individual heights.
Center Anything
The most common flexbox use case. Three lines to perfectly center content:
flex-wrap — Multi-line Flex
By default, flex items squeeze onto one line. Add flex-wrap: wrap to let them break into multiple rows.
flex-grow, flex-shrink, flex-basis
These three properties control how items resize. The shorthand flex: grow shrink basis is almost always what you want.
- flex: 1 — item grows to fill available space
- flex: 0 0 200px — fixed at 200px, no growing or shrinking
- flex: 2 — takes twice as much space as
flex: 1siblings
Common Patterns
Navbar with logo left, links right
Equal-height cards
Frequently Asked Questions
flex-direction: column, they swap roles.display: flex; justify-content: center; align-items: center;. The parent needs a defined height (or the page body does). That is it — works for any content.