CSS Vertical Align
Vertical centering used to be awkward in CSS, but Flexbox and Grid now make it straightforward.
The name vertical-align is a little misleading: as a property it only aligns inline and table-cell content, not block boxes. For centering a box vertically inside its parent, modern layout methods are the reliable choice.
Centering both directions with Flexbox
Flexbox centering
<!DOCTYPE html>
<html>
<head>
<style>
.hero {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
</style>
</head>
<body>
<div class="hero">
<p>Centered content</p>
</div>
</body>
</html>Here justify-content handles the horizontal axis and align-items handles the vertical axis. The parent needs a height for there to be vertical space to center within.
Centering with Grid
One-line grid centering
<!DOCTYPE html>
<html>
<head>
<style>
.hero {
display: grid;
place-items: center;
height: 300px;
}
</style>
</head>
<body>
<div class="hero">
<p>Centered content</p>
</div>
</body>
</html>Note: place-items: center is the shortest way to center a single item both ways, combining align-items and justify-items in one declaration.
The vertical-align property
- middle: aligns the middle of the element with the middle of the surrounding text
- top: aligns the top with the tallest element on the line
- baseline: the default, sits on the text baseline
- bottom: aligns the bottom with the lowest element on the line
Aligning an icon with text
<!DOCTYPE html>
<html>
<head>
<style>
.icon {
vertical-align: middle;
}
td {
vertical-align: top;
}
</style>
</head>
<body>
<p>Look at the <img class="icon" src="star.png" alt="Star" width="20" height="20"> icon next to this text.</p>
<table>
<tr>
<td>Tall cell<br>with two lines</td>
<td>Short cell</td>
</tr>
</table>
</body>
</html>Exercise: CSS Align
How do you horizontally center a block-level element that has a fixed width?