How to emulate background-size: cover on <img>?

Alex picture Alex · Nov 4, 2013 · Viewed 78.8k times · Source

How can I resize and reposition the image inside a box, in such way that it covers the entire box, similar to how background-size: cover works.

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

I know I have to add overflow:hidden to the box and the image needs position: absolute. But what's the formula that gets me the right new size for the image, and left + top positions?

Answer

Danield picture Danield · Oct 6, 2014

For what it's worth: this can now be done with CSS alone with...

The new CSS property object-fit (Current browser support)

Just set object-fit: cover; on the img

You don't even need to wrap the img in a div!

FIDDLE

img {
  width: 100px;
  height: 100px;
}
.object-fit {
  display: block;
  object-fit: cover;
}
.original {
  width: auto;
  height: auto;
  display: block;
}
<img src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Img 'squashed' - not good</p>
<img class="object-fit" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>object-fit: cover -
   The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p>
<img class="original" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Original ing</p>

You can read more about this new property in this webplatform article.

Also, here is a fiddle from the above article which demonstrates all the values of the object-fit property.