Categories
CSS

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

Spread the love

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

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

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

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

For instance, we write

<div class="parent">
  <img class="child" src="https://picsum.photos/300/300" />
</div>

to add a div with an img element inside.

Then we write

.parent {
  align-items: center;
  background: red;
  display: flex;
  height: 250px;
  width: 250px;
}

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

Then we vertically center the img element with align-items: center;.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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