To center text both horizontally and vertically inside a div
, you can use one of these CSS methods:
1. Flexbox (Modern & Recommended)
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 300px; /* Explicit height required */
width: 100%;
}
HTML:
<div class="container">
Centered Text
</div>
2. CSS Grid
.container {
display: grid;
place-items: center; /* Centers both axes */
height: 300px;
}
3. Absolute Positioning + Transform
Works without needing a parent container height:
.container {
position: relative;
height: 300px;
}
.centered-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Adjusts for element's own size */
}
HTML:
<div class="container">
<div class="centered-text">Centered Text</div>
</div>
4. Line-Height (Single-Line Text Only)
.container {
height: 300px;
line-height: 300px; /* Matches container height */
text-align: center;
}
Comparison Table
Method | Best For | Browser Support |
---|---|---|
Flexbox | Modern layouts | All modern browsers |
CSS Grid | Modern layouts | All modern browsers |
Absolute + Transform | Legacy/unknown heights | All browsers |
Line-Height | Single-line text | All browsers |
Full Example (Flexbox)
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
width: 400px;
border: 2px solid #333;
background: #f0f0f0;
}
</style>
</head>
<body>
<div class="container">
Perfectly Centered Text
</div>
</body>
</html>
Key Notes:
- Use Flexbox or Grid for modern projects.
- Use Absolute Positioning for legacy browser support.
- Avoid
line-height
for multi-line text (useflexbox
instead).