How To Center an Image Vertically in CSS

Advertisement

Centering an image vertically can be a bit tricky, but with the right techniques, it can be achieved easily. In this tutorial, we’ll guide you through the process step by step.

Method 1: Flexbox

Flexbox is a powerful CSS layout module that simplifies the process of centering elements. Here’s how you can use flexbox to vertically center an image:

  1. Wrap the image inside a container element, such as a <div>.
<div class="container">
  <img src="your-image-path.jpg" alt="Your Image">
</div>
  1. Apply the following CSS properties to the container:
.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
  1. That’s it! Your image will now be vertically centered within the container.

Method 2: CSS Grid

CSS Grid is another excellent option for centering elements, including images. Here’s how you can use CSS Grid to achieve vertical centering:

  1. Create a container element and apply the following CSS properties:
.container {
  display: grid;
  place-items: center;
}

  1. Place the image directly inside the container.
<div class="container">
  <img src="your-image-path.jpg" alt="Your Image">
</div>

Voila! Your image will now be vertically centered within the container.

Method 3: Positioning and Transforms

If you prefer a more traditional approach, you can use positioning and transforms to center an image vertically. Here’s how you can do it:

  1. Wrap the image inside a container element.
<div class="container">
  <img src="your-image-path.jpg" alt="Your Image">
</div>
  1. Apply the following CSS properties to the container:
.container {
  position: relative;
}

.container img {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

  1. Your image will now be vertically centered within the container.

Method 4: Table Display

Although less commonly used, the table display property can also help you center an image vertically. Here’s how you can do it:

  1. Wrap the image inside a container element.
<div class="container">
  <img src="your-image-path.jpg" alt="Your Image">
</div>
  1. Apply the following CSS properties to the container:
.container {
  display: table;
  height: 100%;
  width: 100%;
}

.container img {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

  1. Your image will now be vertically centered within the container.
author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.