Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 768
Alex Avatar asked Nov 04 '13 20:11

Alex


People also ask

How can I set cover photo on IMG tag?

Just set object-fit: cover; on the img . See MDN - regarding object-fit: cover : The replaced content is sized to maintain its aspect ratio while filling the element's entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

Can you resize background image?

The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.

How does background-size cover work?

If the background-size is contain or cover : While preserving its intrinsic proportions, the image is rendered at the largest size contained within, or covering, the background positioning area. If the image has no intrinsic proportions, then it's rendered at the size of the background positioning area.


1 Answers

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.

like image 112
Danield Avatar answered Sep 19 '22 16:09

Danield