CSS Text Vertical Align Middle in Div
Sometimes you must put text or an image exactly in the middle of a box, from top to bottom. Here are the common CSS ways, from the best to the old ones.
1. Flexbox (best way)
Make the box a flex container and use align-items: center. Add justify-content: center to centre it horizontally too.
<div class="box">Centred text</div>
.box {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
min-height: 120px;
border: 2px solid grey;
}
Output in the browser
Centred text
2. Grid
.box {
display: grid;
place-items: center; /* both directions */
min-height: 120px;
}
3. line-height (only for one line of text)
Set the line-height equal to the height of the box.
.box {
height: 60px;
line-height: 60px;
text-align: center;
border: 2px solid grey;
}
Output in the browser
One line only
4. Absolute position and transform
.box { position: relative; min-height: 120px; }
.box .inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Output in the browser
Centred inner box
5. table-cell (old way)
.outer { display: table; width: 100%; height: 120px; }
.inner { display: table-cell; vertical-align: middle; }
Note:
Use Flexbox or Grid in new projects. The other methods are for very old browsers or special cases. Also see How to center a div in CSS?
Learn more about the similar topics:
| Tutorials |
|---|
| CSS Layout – The display Property |
| CSS Position Property |
| CSS z-index |
| CSS Float and Clear Property |
| Exercises & Assignments |
|---|
| Write CSS to centre a box horizontally using margin auto |
| Write CSS to create a horizontal navigation menu |