How to vertically align an image inside a div with responsive height with CSS?

Spread the love

Sometimes, we want to vertically align an image inside a div with responsive height with CSS.

In this article, we’ll look at how to vertically align an image inside a div with responsive height with CSS.

How to vertically align an image inside a div with responsive height with CSS?

To vertically align an image inside a div with responsive height with CSS, we use flexbox.

For instance, we write

<div class="img-container">
  <img src="https://picsum.photos/200/300" alt="" />
</div>

to add a div with an img element inside.

Then we write

.img-container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

to make the div a flex container with display: flex;.

Then we center its content horizontally with justify-content: center;.

And we center its content vertically with align-items: center;.

Conclusion

To vertically align an image inside a div with responsive height with CSS, we use flexbox.

Leave a Reply

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