How to Center an Element Vertically Using CSS (Vertical Alignment)
Last updated: 21.02.2026
Views: 208
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:
-
Infinite Rotation with CSS Animation
An infinitely rotating element on a website is an interesting way to attract the user's attention. It is quite easy to implement such an element using CSS. Here is an exa...
-
How to Add a Favicon to a Website
A favicon is a website icon. The easiest way to add it to the page is to put an icon with the name favicon.ico 16x16 pixels in the root of the site. Or set a path by writ...
-
Image Scaling Problem in Outlook
When I was composing HTML emails, I encountered the fact that in desktop Outlook (it turns out that someone else uses it) the images were displayed at a strange scale. Al...
Leave a Reply