W3docs

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

In this snippet, we’ll show how you can set an equivalent of the “cover” value of the background-size property for the <img> tag. Use the object-fit property.

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. You can also use the object-position property to fine-tune which part of the image is visible when it’s cropped.

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

Example of styling the <img> tag 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: 66.66% 0;
        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 used width and height of 0 with percentage padding to maintain the image’s aspect ratio. Note that percentage values in padding are calculated relative to the element’s width, so this technique creates a box that scales proportionally to the placeholder image’s dimensions.