How to align an image in the center and middle within div with CSS?

Spread the love

Sometimes, we want to align an image in the center and middle within div with CSS.

In this article, we’ll look at how to align an image in the center and middle within div with CSS.

How to align an image in the center and middle within div with CSS?

To align an image in the center and middle within 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 {
  display: flex;
  height: 300px;
  background-color: #000;
  align-items: center;
  justify-content: center;
}

.child {
  width: 100px;
  height: 100px;
  margin: auto;
}

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

And we center the content vertically and horizontally in the div with align-items: center; and justify-content: center; respectively.

Conclusion

To align an image in the center and middle within div with CSS, we use flexbox.

Leave a Reply

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