How to Center an Element Vertically Using CSS (Vertical Alignment)
Last updated: 21.02.2026
Views: 385
There are several ways of vertical alignment. In different situations, different ways are suitable. Consider some of them.
1. Using Flexbox
The easiest and most widely used method:
.container {
display: flex;
align-items: center; /* Centers vertically */
justify-content: center; /* Optional: Centers horizontally */
height: 100vh; /* Full viewport height, if needed. Or set your own height */
}
2. Using Grid
CSS Grid also makes vertical centering straightforward:
.container {
display: grid;
place-items: center; /* Centers both vertically and horizontally */
height: 100vh; /* Full viewport height, if needed. Or set your own height */
}
With Grid you can also use align-items: center instead of place-items: center
3. Using position and transform
For situations where Flexbox or Grid isn’t ideal:
.element {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
This method centers the element relative to its containing block.
4. Using line-height (Single-Line Content)
If you’re centering single-line content:
.container {
height: 100px; /* Example height */
line-height: 100px; /* Match the height */
text-align: center; /* Optional: Centers horizontally */
}
This only works for single-line text elements.
5. Using table-cell Display
For compatibility with older browsers:
.container {
display: table;
height: 100vh; /* Full viewport height, if needed. Or set your own height */
width: 100%; /* Optional */
}
.element {
display: table-cell;
vertical-align: middle;
text-align: center; /* Optional: Centers horizontally */
}
Which Method to Use?
- Use
FlexboxorGridfor modern layouts. - Use
position + transformfor specific scenarios or absolute positioning. - Use
line-heightto center single-line text.
Similar posts:
-
How to Hide Scrollbar Using CSS
There are several ways to hide the scrollbar using CSS, depending on whether you want to completely remove scrolling or just hide the visual appearance of the scrollbar. ...
-
How to Create a Drop Down Menu Using only HTML and CSS
In one of the previous articles, we looked at creating a drop down menu using JavaScript (jQuery). In this article, we will look at how to make a drop down menu using onl...
-
Image Scaling Problem in Outlook
Creating HTML email layouts is a fairly complex and not always enjoyable process. This is mainly due to the fact that many email clients do not support modern web standar...
Leave a Reply