CSS Flexbox: The Complete Guide with Examples
Flexbox is the modern one-dimensional layout model in CSS. It replaces float-based layouts with simpler, more predictable code.
The Flex Container
.container {
display: flex;
}This enables flex context for all direct children.
Main Axis vs Cross Axis
Flexbox works along two axes:
- Main axis — direction set by
flex-direction(default: row, left to right) - Cross axis — perpendicular to main axis
Key Properties
On the Parent
| Property | Options | What It Does |
|---|---|---|
flex-direction | row (default), column, row-reverse, column-reverse | Sets main axis direction |
justify-content | flex-start, center, space-between, space-around, space-evenly | Aligns items along main axis |
align-items | stretch, center, flex-start, flex-end, baseline | Aligns items along cross axis |
flex-wrap | nowrap, wrap, wrap-reverse | Allows items to wrap to next line |
gap | any CSS length | Spacing between items |
On the Children
| Property | What It Does |
|---|---|
flex-grow | How much the item grows relative to siblings |
flex-shrink | How much the item shrinks relative to siblings |
flex-basis | Initial size before growing or shrinking |
align-self | Overrides parent’s align-items for this item |
order | Changes visual order (default 0) |
Common Layouts
Navigation Bar
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}Card Grid
.grid {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.card {
flex: 1 1 300px;
}Centered Content
.center {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}Holy Grail Layout
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
display: flex;
flex: 1;
}
nav, aside {
flex: 0 0 200px;
}
article {
flex: 1;
}Flexbox vs Grid
| Flexbox | CSS Grid |
|---|---|
| One-dimensional (row OR column) | Two-dimensional (row AND column) |
| Content-driven | Layout-driven |
| Best for nav bars, centering, small components | Best for page layouts, complex grids |
Start with centering: See our guide on how to center a div.