How to fit an image (img) inside a div and keep the aspect ratio with CSS?

Spread the love

Sometimes, we want to fit an image (img) inside a div and keep the aspect ratio with CSS.

In this article, we’ll look at how to fit an image (img) inside a div and keep the aspect ratio with CSS.

How to fit an image (img) inside a div and keep the aspect ratio with CSS?

To fit an image (img) inside a div and keep the aspect ratio with CSS, we set the width and height to 100%.

For instance, we write

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

to set its width and height to 100% to keep the aspect ratio.

We use object-fit: contain; to keep it inside the container.

Conclusion

To fit an image (img) inside a div and keep the aspect ratio with CSS, we set the width and height to 100%.

Leave a Reply

Your email address will not be published.