The most powerful layout tool in CSS. Master it once — use it everywhere.
I used to spend hours trying to center a div. Trying margin. Trying padding. Trying random pixel values. Nothing worked. Then I learned CSS Flexbox — and layouts finally made sense. This is the guide I wish I had when I started.
What is CSS Flexbox?
Flexbox is a one-dimensional layout system. It lets you arrange items in a row OR a column — and control how they align, space out and wrap.
The key idea: you apply Flexbox to the parent container — not the children. The parent controls. The children follow.
Key Properties You Must Know
Property
What It Does
Values
display: flex
Activates Flexbox
flex
justify-content
Horizontal alignment
center | space-between | flex-start
align-items
Vertical alignment
center | flex-start | flex-end
flex-direction
Row or column layout
row | column
flex-wrap
Wrap to next line
wrap | nowrap
gap
Space between items
16px | 1rem
Center Anything — Perfectly
This is the most searched CSS trick on the internet. With Flexbox it takes 3 lines:
Every navigation bar you have ever seen uses this exact pattern:
CSS
/* Navigation bar */.navbar {
display: flex;
justify-content: space-between; /* logo left, links right */align-items: center;
padding: 16px 32px;
}
/* Card row — responsive */.cards {
display: flex;
flex-wrap: wrap; /* moves to next line on mobile */gap: 16px;
}
Pro Tips
Pro Tip #1 — Always apply to parent
This is the #1 mistake beginners make. display: flex goes on the parent container — not the child you want to move. The parent controls everything.
Pro Tip #2 — space-between is your best friend
justify-content: space-between is the most used Flexbox value in real projects. It pushes items to opposite ends with equal space between them. Perfect for navbars and card rows.
Pro Tip #3 — flex-wrap makes it responsive
Add flex-wrap: wrap and your items automatically move to the next line when there is not enough space. This one property makes your layout mobile-friendly instantly.
Quick Reference Cheatsheet
CSS CHEATSHEET
display: flex; /* activate flexbox */justify-content: center; /* horizontal center */justify-content: space-between; /* space between items */justify-content: flex-start; /* align left */align-items: center; /* vertical center */align-items: flex-start; /* align top */flex-direction: row; /* horizontal (default) */flex-direction: column; /* vertical */flex-wrap: wrap; /* responsive wrapping */gap: 16px; /* space between items */flex: 1; /* fill available space */