Z
Vertically centering text inside a <div>
has long been one of the most common layout needs in CSS design — and also one of the most misunderstood. Whether you’re building a hero section, a card layout, or a banner, aligning your text perfectly in the center makes your design look balanced and clean.
In this blog post, we’ll cover the best ways to vertically center text inside a div
using CSS, with clear examples and practical advice.
✅ Method 1: Using Flexbox (Best Practice for Modern Layouts)
🔧 CSS Code:
.div-center {
display: flex;
align-items: center; /* Vertical center */
justify-content: center; /* Horizontal center (optional) */
height: 200px;
background-color: #f3f3f3;
border: 1px solid #ccc;
}
✅ HTML Code:
<div class="div-center">
<p>Centered Text</p>
</div>
✔️ Why It Works: Flexbox treats the container as a flexible box. align-items: center
aligns content vertically, while justify-content: center
centers it horizontally.
✅ Method 2: Using CSS Grid (Clean and Powerful)
🔧 CSS Code:
.div-grid {
display: grid;
place-items: center;
height: 200px;
background-color: #e6f7ff;
}
✅ HTML Code:
<div class="div-grid">
<p>Text in the Center</p>
</div>
✔️ Why It Works: place-items: center
is a shorthand for vertical and horizontal centering in grid layout.
✅ Method 3: Using Line-Height (For Single-Line Text Only)
🔧 CSS Code:
.div-lineheight {
height: 100px;
line-height: 100px; /* Equal to height */
text-align: center;
background: #ffe58f;
}
✅ HTML Code:
<div class="div-lineheight">
Single-line Centered Text
</div>
⚠️ Limitation: This only works for single-line text. If the text wraps or has multiple lines, it won’t stay centered vertically.
✅ Method 4: Table-Cell Technique (Good for Legacy Support)
🔧 CSS Code:
.outer {
display: table;
height: 150px;
width: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
text-align: center;
}
✅ HTML Code:
<div class="outer">
<div class="inner">
Centered Text in Table-Cell
</div>
</div>
✔️ Why It Works: This mimics the vertical alignment behavior of HTML tables and is useful for legacy browser support (like IE9 and below).
❌ Common Pitfalls to Avoid
Mistake | Why It’s a Problem |
---|---|
Using only margin-top | It’s not responsive or scalable |
Forgetting to set height | Centering won’t work without fixed height |
Using position: absolute | Risk of overlapping content on resize |
🔚 Conclusion
Vertically centering text in a div
is no longer difficult or confusing. With modern CSS techniques like Flexbox and Grid, you can center content with just a few lines of code. Older techniques like line-height or table-cell are still useful in specific cases.
📌 Quick Comparison Table
Method | Multi-line Support | Modern? | Best Use Case |
---|---|---|---|
Flexbox | ✅ | ✅ | General layouts |
Grid | ✅ | ✅ | Clean and simple centering |
Line-height | ❌ | ✅ | Single-line buttons or labels |
Table-cell | ✅ | ⚠️ | Legacy browser compatibility |