I have a site with many pages and different background pictures, and I display them from CSS like:
body.page-8 {
background: url("../img/pic.jpg") no-repeat scroll center top #000;
background-size: cover;
}
However, I want to show different (fullscreen) pictures on one page using <img>
elements, and I want them to have the same properties as the above background-image: cover;
property (the images cant be displayed from CSS, they must be displayed from the HTML document).
Normally I use:
div.mydiv img {
width: 100%;
}
Or:
div.mydiv img {
width: auto;
}
to make the picture full and responsive. However the picture shrinks too much (width: 100%
) when the screen gets too narrow, and shows the body's background-color in the bottom screen. The other method, width: auto;
, only makes the image full size and does not respond to the screen size.
Is there a way to display the image the same way that background-size: cover
does?
Best Answer
Solution #1 - The object-fit property (Lacks IE support)
Just set
object-fit: cover;
on the img .See MDN - regarding
object-fit: cover
:And for
object-fit: contain
:Also, see this Codepen demo which compares
object-fit: cover
applied to an image withbackground-size: cover
applied to a background imageSolution #2 - Replace the img with a background image with css