To vertically center text (or any inline/inline-block element) in CSS, here are the most reliable methods:
1. Flexbox (Modern & Recommended)
Use Flexbox on the parent container:
.container {
display: flex;
align-items: center; /* Vertical centering */
justify-content: center; /* Horizontal centering (optional) */
height: 200px; /* Required height */
}
Example:
<div class="container">
<p>Centered text</p>
</div>
2. CSS Grid
Use Grid on the parent container:
.container {
display: grid;
place-items: center; /* Centers both vertically and horizontally */
height: 200px;
}
3. Line-Height (Single Line of Text Only)
If the container has a fixed height, match line-height
to the height:
.container {
height: 200px;
line-height: 200px; /* Matches container height */
}
4. Transform & Positioning (Dynamic Heights)
For unknown parent/child heights:
.container {
position: relative;
height: 200px;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
5. Table-Cell Method
Use vertical-align: middle
with display: table-cell
:
.container {
display: table-cell;
vertical-align: middle;
height: 200px;
}
6. Padding (Equal Top/Bottom)
Manually add padding if the container height is known:
.container {
padding: 80px 0; /* 80px top + 80px bottom = 160px total height */
height: 0; /* Adjust as needed */
}
Key Notes
- Flexbox/Grid: Best for modern browsers and dynamic content.
- Line-Height: Only works for single-line text.
- Transform: Works with unknown/dynamic heights.
- Always ensure the parent container has a defined height.
Examples in Action
Flexbox Example:
<div class="container" style="display: flex; align-items: center; height: 300px;">
<p>Vertically centered text</p>
</div>
CSS Grid Example:
<div class="container" style="display: grid; place-items: center; height: 300px;">
<p>Centered text</p>
</div>
Browser Support
Method | Browser Support |
---|---|
Flexbox | Modern browsers |
CSS Grid | Modern browsers |
Transform | IE9+ |
Table-Cell | All browsers |
Recommendation
Use Flexbox for simplicity and flexibility, or CSS Grid if you need a more complex layout. For legacy support, combine transform
with position: absolute
.