Solution #1 – The object-fit property (Lacks IE support)
Just set object-fit: cover;
on the img .
body {
margin: 0;
}
img {
display: block;
width: 100vw;
height: 100vh;
object-fit: cover; /* or object-fit: contain; */
}
<img src="http://lorempixel.com/1500/1000" />
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.
And for object-fit: contain
:
The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be “letterboxed” if its aspect ratio does not match the aspect ratio of the box.
Also, see this Codepen demo which compares object-fit: cover
applied to an image with background-size: cover
applied to a background image
Solution #2 – Replace the img with a background image with css
body {
margin: 0;
}
img {
position: fixed;
width: 0;
height: 0;
padding: 50vh 50vw;
background: url(http://lorempixel.com/1500/1000/city/Dummy-Text) no-repeat;
background-size: cover;
}
<img src="http://placehold.it/1500x1000" />