css

How to Center an Element Vertically Using CSS (Vertical Alignment)

Last updated: 21.02.2026
Views: 274

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 Flexbox or Grid for modern layouts.
  • Use position + transform for specific scenarios or absolute positioning.
  • Use line-height to center single-line text.
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

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 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 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...

Leave a Reply

Your email address will not be published. Required fields are marked *