How To Center an Image Vertically in CSS
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:
- Wrap the image inside a container element, such as a
<div>
.
<div class="container">
<img src="your-image-path.jpg" alt="Your Image">
</div>
- Apply the following CSS properties to the container:
.container {
display: flex;
align-items: center;
justify-content: center;
}
- 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:
- Create a container element and apply the following CSS properties:
.container {
display: grid;
place-items: center;
}
- 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:
- Wrap the image inside a container element.
<div class="container">
<img src="your-image-path.jpg" alt="Your Image">
</div>
- Apply the following CSS properties to the container:
.container {
position: relative;
}
.container img {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
- 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:
- Wrap the image inside a container element.
<div class="container">
<img src="your-image-path.jpg" alt="Your Image">
</div>
- 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;
}
- Your image will now be vertically centered within the container.