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?
I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.
Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.
background-size: cover
The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to
transform: scale(0.1)
).The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)
background-size: contain
Following the same principle, you can also use it to emulate
background-size: contain
:I know this is old, however many solutions I see above have an issue with the image/video being too large for the container so not actually acting like background-size cover. However, I decided to make "utility classes" so that it would work for images and videos. You simply give the container the class .media-cover-wrapper and the media item itself the class .media-cover
Then you have the following jQuery:
When calling it make sure to take care of page resizing:
Then the following CSS:
Yeah it may require jQuery but it responds quite well and acts exactly like background-size: cover and you can use it on image and/or videos to get that extra SEO value.