How to Set an Equivalent of the "cover" Value of the background-size Property for an <img> Tag

It is possible to use an equivalent of the CSS background-size property’s “cover” value on the HTML <img> tag. Here, we’ll show two methods.

Solutions with CSS properties

You can set an image by using the <img> tag and set the object-fit property to “cover”.

Example of using the object-fit property on the <img> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        margin: 0;
      }
      img {
        display: block;
        width: 100vw;
        height: 100vh;
        object-fit: cover;
      }
    </style>
  </head>
  <body>
    <img src="https://images.unsplash.com/photo-1510172951991-856a654063f9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" />
  </body>
</html>

In the example above, we also specified the width and height of the image and set the display property to “block”. Here, the content is sized to preserve its aspect ratio while filling the whole content-box of the element.

Let’s see another example, where we replace the <img> with a background image.

Example of replacing the <img> with a background image:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        margin: 0;
      }
      img {
        position: fixed;
        width: 0;
        height: 0;
        padding: 40vh 40vw;
        background: url(https://images.unsplash.com/photo-1491796014055-e6835cdcd4c6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60) no-repeat;
        background-size: cover;
      }
    </style>
  </head>
  <body>
    <img src="http://placehold.it/1500x1000" alt="Background-size example" />
  </body>
</html>

Here, we set a background image with the background property, then, specified the background-size property with the “cover” value. Also, we set the position to “fixed” and added the width, height, and padding properties.


Do you find this helpful?

Related articles