How to center an image horizontally within a div with CSS?

Spread the love

Somewtimees, we want to center an image horizontally within a div with CSS.

In this article, we’ll look at how to center an image horizontally within a div with CSS.

How to center an image horizontally within a div with CSS?

To center an image horizontally within a div with CSS, we use flexbox.

For instance, we write

<div style="border: 1px solid red">
  <img
    src="https://picsum.photos/200/300"
    alt=""
    srcset=""
    style="
      border-radius: 50%;
      height: 7.5rem;
      width: 7.5rem;
      object-fit: contain;
    "
  />
</div>

to add a div with an image inside.

Then we write

div {
  display: flex;
  justify-content: center;
  align-items: center;
}

div img {
  object-fit: contain;
}

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

Then we center the contents inside horizontally and vertically with justify-content: center; and align-items: center; respectively.

And then we make the img element fit in the container with object-fit: contain;.

Conclusion

To center an image horizontally within a div with CSS, we use flexbox.

Leave a Reply

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