How to add the equivalent of background-size: cover and contain for image elements with CSS?

Spread the love

Sometimes, we want to add the equivalent of background-size: cover and contain for image elements with CSS.

In trhis article, we’ll look at how to add the equivalent of background-size: cover and contain for image elements with CSS.

How to add the equivalent of background-size: cover and contain for image elements with CSS?

To add the equivalent of background-size: cover and contain for image elements with CSS, we use the object-fit property.

For instance, we write

<img src="https://picsum.photos/200/3000" />

to add an img element.

Then we write

body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover;
}

to add object-fit: cover to make the img element fit to its container.

Conclusion

To add the equivalent of background-size: cover and contain for image elements with CSS, we use the object-fit property.

Leave a Reply

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