img
with srcset
attribute looks like a great way of doing responsive images. Is there an equivalent syntax that works in css background-image
property?
HTML
<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">
CSS
.mycontainer {
background: url(?something goes here?);
}
For a polyfill, you can use an img with srcset as a mechanism for downloading the correct image size, then use JS to hide it and set the background-image of a parent element.
Here's a fiddle: http://jsbin.com/garetikubu/edit?html,output
The use of
onload
and putting the JS as a blocking script in the<head>
is important. If you put the script later (say at the end of<body>
), you can get a race condition where img.currentSrc hasn't been set yet by the browser. It's best to wait for it to be loaded.The example allows you to see the original img being downloaded. You can easily hide it with some CSS.
Another approach, which is quite frankly more robust, would be to adapt the characteristics and options of background images to an image with the srcset attribute.
To do this, set the image to be width: 100%; height: 100%; and object-fit: cover or contain.
Here is an example:
This may not be the best approach for everyone but I imagine it will get most the desired results without any javascript workaround.
Based on @Weston's answer, I've built a more general jQuery solution, you can basically just copy&paste the JS and CSS and focus on the HTML part ;)
TL;DR - fiddle: https://jsfiddle.net/dpaa7oz6/
CSS
...to ensure images will be hardly visible while loading
JS / jQuery
This script will go through all images that have
srcSet
class and bindload
event that takescurrentSrc
(orsrc
if not supported) and puts it as abackground-image
CSS to the closest parent withbgFromSrcSet
class.That itself would not be enough! So it also puts an interval checker on
window
load
event to test if the load events have been completed, if not, it triggers them. (img
load
event is very often trigger only on first-time load, on following loads, image source could be retrieved from cache, resulting in img load event NOT being fired!)HTML
...could look like this:
Note: class
bgFromSrcSet
must not be set to theimg
itself! It can only be set to the elements in theimg
DOM parent tree.image-set
is the equivalent CSS feature. We should add equivalent srcset functionality (defining resources according to their dimensions) to the spec.Currently it's only implemented in Safari, Chrome and Opera with the
-webkit-
prefix, and it's only support thex
descriptors.If you are using Foundation framework (https://foundation.zurb.com/), you can use Interchange plugin for that:
https://foundation.zurb.com/sites/docs/interchange.html#use-with-background-images
You can use media queries for your purpose. It's easy as this:
And I think it works on every browser who support media queries ;)