π Introduction
One of the most common layout challenges in CSS is **vertically centering content**. Flexbox makes this incredibly simple with just a couple of properties. Whether you're centering text, buttons, cards, icons, or entire sections, Flexbox gives you clean, predictable, and responsive vertical alignment. π‘β¨
π― What Does Vertical Centering Mean?
Vertical centering means placing an element **perfectly in the middle** (top-to-bottom) of its parent container.
π₯ The Flexbox Properties You Need
1. display: flex
Turns the parent container into a flexible box.
2. align-items: center
Centers children along the **cross axis** (vertical axis by default).
Basic Vertical Center
.parent {
display: flex;
align-items: center;
height: 300px;
background: #f3f4f6;
}
.child {
background: #4f46e5;
color: white;
padding: 20px;
border-radius: 8px;
}β¨ Vertical + Horizontal Center (Most Common)
To center in *both directions*, add justify-content: center.
Center Both Ways
.parent {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
height: 300px;
background: #e5e7eb;
}
.child {
padding: 20px 30px;
background: #2563eb;
color: white;
border-radius: 8px;
}π¦ Centering Text Vertically
Text Only
.text-box {
display: flex;
align-items: center;
height: 100px;
font-size: 20px;
background: #fef3c7;
}π Centering Multiple Items Vertically
You can also align multiple flex children vertically.
Multiple Items
.nav {
display: flex;
align-items: center;
height: 60px;
background: #111827;
}
.nav a {
color: white;
margin-right: 20px;
}π§© Centering in Column Direction
When using flex-direction: column, vertical and horizontal axes switch.
Column Centering
.column-center {
display: flex;
flex-direction: column;
justify-content: center; /* vertical in column */
height: 300px;
}π§ Common Mistakes
- Forgetting to set height on parent
- Using
align-itemswhen you meantjustify-content - Not setting display: flex on parent
- Confusing main axis vs cross axis
π Quick Reference Cheatsheet
| Goal | Properties |
|---|---|
| Vertical center | align-items: center |
| Horizontal center | justify-content: center |
| Center both ways | align-items: center; justify-content: center; |
| Column direction vertical center | justify-content: center |
π Conclusion
Using Flexbox for vertical centering is one of the cleanest and most powerful layout techniques in CSS. With display: flex and align-items: center, you can create vertically aligned layouts with ease β no hacks, no transforms, no absolute positioning. Master this, and your UI layouts become cleaner, scalable, and responsive. β¨