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?
Solution #1 - The object-fit property (Lacks IE support)
Just set
object-fit: cover;
on the img .See MDN - regarding
object-fit: cover
: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
What you could do is use the 'style' attribute to add the background image to the element, that way you will still be calling the image in the HTML but you will still be able to use the background-size: cover css behaviour:
HTML:
CSS:
This is how I add the background-size: cover behaviour to elements that I need to dynamically load into HTML. You can then use awesome css classes like background-position: center. boom
im not allowed to 'add a comment' so doing this , but yea what Eru Penkman did is pretty much spot on , to get it like background cover all you need to do is change
TO
We can take ZOOM approach. We can assume that max 30% (or more upto 100%) can be the zooming effect if aspect image height OR width is less than the desired height OR width. We can hide the rest not needed area with overflow: hidden.
This will adjust images with different width OR height.
encountered same exact symptops. above worked for me.
I needed to emulate
background-size: contain
, but couldn't useobject-fit
due to the lack of support. My images had containers with defined dimensions and this ended up working for me: