CSS
How to Align Text Vertically Center in a Div Element Using CSS
One of the most common tasks in web design is vertically centering text inside a div
. Whether you’re building a landing page, button, or card component, centered text creates a clean and balanced layout.
Thankfully, modern CSS offers several efficient ways to align text vertically within a div
. In this article, we’ll explore best practices and real code examples to help you center text like a pro.
β Method 1: Using Flexbox (Most Popular)
πΉ HTML
<div class="flex-box">
<p>Vertically centered text</p>
</div>
πΉ CSS
.flex-box {
display: flex;
align-items: center; /* Align vertically */
justify-content: center; /* Align horizontally (optional) */
height: 200px;
border: 2px solid #4caf50;
}
β Why Use It?
- Works for both vertical and horizontal centering
- Responsive and modern
- Clean, readable code
β Method 2: Using Grid Layout
πΉ HTML
<div class="grid-box">
<p>Centered using CSS Grid</p>
</div>
πΉ CSS
.grid-box {
display: grid;
place-items: center; /* align-items + justify-items */
height: 200px;
border: 2px dashed #2196f3;
}
π‘ Benefits
- Very concise
- Perfect for simple centering tasks
- Ideal when you donβt need complex layout control
β Method 3: Using Line-Height (Only for Single Line Text)
πΉ HTML
<div class="line-height-box">Centered Text</div>
πΉ CSS
.line-height-box {
height: 100px;
line-height: 100px; /* Match the height */
text-align: center;
border: 2px dotted #ff9800;
}
β οΈ Caution
- Only works properly for single-line text
- Not suitable for multi-line paragraphs
β Method 4: Table-Cell Technique (Legacy-Compatible)
πΉ HTML
<div class="table-cell-box">
<p>Using table-cell alignment</p>
</div>
πΉ CSS
.table-cell-box {
display: table-cell;
vertical-align: middle;
height: 150px;
width: 100%;
text-align: center;
border: 1px solid #ccc;
}
π Use Case
- Great for older browser support
- Slightly outdated in modern layouts
π Comparison Table
Method | Multi-line Support | Modern Support | Code Simplicity |
---|---|---|---|
Flexbox | β | β | β |
CSS Grid | β | β | β |
Line-height | β | β | β |
Table-cell | β | β | β (verbose) |
π§Ύ Final Thoughts
If you’re working with modern browsers, Flexbox and Grid are the best tools for vertically centering text inside a div
. Theyβre clean, flexible, and easy to maintain. For single-line text, the line-height
trick is quick and effective. And when you need backward compatibility, the table-cell
method is still a solid option.
Pro Tip: Combine vertical and horizontal centering to ensure your text looks centered across all screen sizes and resolutions.