In this blog post, we’ll explore several ways to vertically center text using CSS. While it may seem like a trivial task, vertically centering elements, including text, can often be a bit tricky in CSS. Don’t worry, by the end of this post, you’ll know several ways to tackle this challenge!
Method 1: Using Line-Height
The simplest way to vertically center a single line of text is by using the line-height
property. This works best when you know the height of the containing element.
.container {
height: 100px;
}
.text {
line-height: 100px;
}
The limitations with this approach is that once text spans over 2 lines, the strategy crumbles because no there’s a 100px
gap between your lines.
Method 2: Using Padding
Another way to vertically center text is by using equal top and bottom padding. This method works well when you don’t know the height of the container.
.container {
padding: 20px 0;
}
In this example, container
will be vertically centered. This is pretty much the easiest way to center content and text. It centers text within the context of the container, though. So it’s not as flexible as other solutions.
Method 3: Using Flexbox
Flexbox is a powerful tool in CSS that can make vertical centering (and many other layout challenges) a breeze.
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
}
In this example, align-items: center;
vertically centers the text and justify-content: center;
horizontally centers it. Additionally, you can text-align: center;
to really round out the centering pattern.
Keep in mind, justify-content: center;
and text-align: center;
are optional if your objective is to vertically center content.
Method 4: Using CSS Grid
Similar to Flexbox, CSS Grid is also a great way to center text both vertically and horizontally.
.container {
display: grid;
align-items: center;
justify-content: center;
height: 100px;
}
Similar to Flexbox, align-items: center;
vertically centers the text and justify-content: center;
horizontally centers it. CSS grid provides other benefits for general layout considerations.
Method 5: Using Position and Transform
This method works in all scenarios, even when you don’t know the height of the container.
.container {
position: relative;
}
.text {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
In this method, position: relative;
is set on the container, and position: absolute;
on the text. top: 50%;
moves the text down by 50% of the container’s height, and ``transform: translateY(-50%);` moves the text up by 50% of its own height, achieving perfect vertical centering.