Here’s your complete CSS Flexbox Guide — ideal for beginners and intermediate web developers looking to master layout with Flexbox!
🧱 What is Flexbox?
Flexbox (Flexible Box Layout) is a one-dimensional layout system in CSS that helps you design layouts where elements align and distribute space dynamically — either horizontally (row) or vertically (column).
Flexbox is perfect for:
Navigation bars
Cards in rows or columns
Centering elements
Equal-height columns
🧩 Flexbox Terminology
Term | Description |
---|---|
Flex Container | The parent element with display: flex |
Flex Items | The direct children of the flex container |
Main Axis | Direction items are placed in (row by default) |
Cross Axis | Perpendicular to main axis |
⚙️ Step 1: Set Up a Flex Container
.container {
display: flex;
}
By default, items will be placed in a row (horizontally).
🧭 Step 2: Direction and Wrapping
.container {
flex-direction: row | column | row-reverse | column-reverse;
flex-wrap: nowrap | wrap | wrap-reverse;
}
row
(default): Left to rightcolumn
: Top to bottomwrap
: Items wrap to next line when needed
🎯 Step 3: Main Axis Alignment
.container {
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
}
Aligns items horizontally (main axis).
🎯 Step 4: Cross Axis Alignment
.container {
align-items: stretch | flex-start | flex-end | center | baseline;
}
Aligns items vertically (cross axis).
🧱 Step 5: Aligning Individual Items
.item {
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
Overrides align-items
for just one item.
📐 Step 6: Controlling Item Size & Growth
.item {
flex-grow: 1; /* grows to fill space */
flex-shrink: 1; /* shrinks when needed */
flex-basis: 200px; /* default size before growing/shrinking */
}
Or shorthand:
.item {
flex: 1 0 200px; /* grow | shrink | basis */
}
⬆️ Order of Items
.item {
order: 2;
}
Default is
0
. Lower numbers come first.
💡 Common Layouts with Flexbox
✅ Center Anything
.container {
display: flex;
justify-content: center;
align-items: center;
}
✅ Equal Width Columns
.container {
display: flex;
}
.item {
flex: 1;
}
✅ Responsive Wrapping Grid
.container {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.item {
flex: 1 1 200px;
}
🧪 Try It Live (Free Tools)
🧠 Pro Tips
Use
gap
instead ofmargin
between flex items (modern browsers)Use
min-width
andmax-width
for responsive flexibilityCombine
flex
withmedia queries
for responsive designDon’t mix
float
andflexbox
— it’s cleaner without float