🚀 Getting Started
The Magic Line
Add this to any container to enable flexbox:
display: flex;
That's it. Everything inside becomes a flex item.
💡 Key Concept
Flexbox has a
main axis (default: horizontal) and a
cross axis (default: vertical). Most properties control alignment along one of these axes.
📦 Container Properties
Apply these to the parent element (the flex container)
flex-direction
Which way do items flow?
row (default)
row-reverse
column
column-reverse
justify-content
Align items along the MAIN axis (horizontal by default)
flex-start (default)
flex-end
center
space-between
space-around
space-evenly
justify-content: space-between;
align-items
Align items along the CROSS axis (vertical by default)
flex-start
flex-end
center
stretch (default)
baseline
flex-wrap
Should items wrap to the next line?
nowrap (default)
wrap
wrap-reverse
gap
Space between items (the easy way)
gap: 10px;
gap: 10px 20px;
row-gap: 10px;
column-gap: 20px;
gap: 15px;
🧩 Item Properties
Apply these to child elements (the flex items)
flex-grow
How much should this item grow relative to others?
0 (default - don't grow)
1 (grow equally)
2 (grow twice as much)
.middle { flex-grow: 2; }
flex-shrink
How much should this item shrink when space is tight?
1 (default - shrink equally)
0 (don't shrink)
2 (shrink twice as much)
flex-basis
Starting size before growing/shrinking
auto (default)
200px
50%
0
flex (shorthand)
Combines grow, shrink, and basis in one line
flex: 1;
flex: 1 0 200px;
align-self
Override align-items for one specific item
auto (default)
flex-start
flex-end
center
stretch
🎯 Common Patterns
Center Everything
The holy grail of CSS — centering vertically AND horizontally
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Navigation Bar
Logo on left, links on right
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
Equal Width Columns
Three columns that share space equally
.container { display: flex; gap: 20px; }
.column { flex: 1; }
Footer at Bottom
Push footer to bottom even with little content
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }
💡 When to Use Flexbox vs Grid
Flexbox: One-dimensional layouts (row OR column). Navigation, toolbars, centering, card layouts.
Grid: Two-dimensional layouts (rows AND columns). Page layouts, image galleries, complex forms.