How to Center an Element Vertically Using CSS (Vertical Alignment)
Last updated: 21.02.2026
Views: 379
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:
-
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...
-
How to Add a Favicon to a Website
A favicon (short for “favorite icon”) is a small graphical icon associated with a website. It is displayed in browser tabs, bookmarks, history lists, and sometimes in sea...
-
Infinite Rotation with CSS Animation
One simple yet effective technique is creating an infinitely rotating element. This kind of animation can be used to attract attention to specific parts of a page, such a...
Leave a Reply