I am fairly new to the frontend and css. I am trying to add a background-image in such a way that, if .avif files are supported, then these are loaded. Otherwise fallback to a .png file. I'm wondering if it is possible to do this without javascript and without loading all the images to not affect page speed. I am running Chrome 107.0.5304.110, ios 16.1 in (mostly)simulator (I know older versions of ios dont support avif, but the latest one does. Would like something that works with both) , and Firefox 106.0.1.
Attempt 1 follows this previous answer. Note the usage of webkit-image-set. Here is my code:
background-image: url("/static/img/image.png");
background-image: -webkit-image-set(url("/static/img/image.avif")1x );
Doing this works for Chrome and Firefox, but Safari on ios shows a gray image.
Attempt 2 follows the answer on this blog. Note that here image-set is used. Code:
background-image: url("/static/img/image.png");
background-image: image-set(
url("/static/img/image.avif") 1x,
url("/static/img/image.png") 1x,
);
This is visible on all three browsers, but the png is always shown. I also invert the positions in the image-set but same results. Always png.
Attempt 3, a slight variation of attempt 2. I just change the format on the first line.
background-image: url("/static/img/image.avif");
background-image: image-set(
url("/static/img/image.avif") 1x,
url("/static/img/image.png") 1x,
);
This works well on chrome/firefox, but ios is gray.
Is there a way to solve this problem? Thanks!
It seem's that image-set are partially supported on Safari browsers,
source
caniuse
You can simply use
background-image:
url("/static/img/image.avif"),
url("/static/img/image.jpeg");
you can test on sandbox below that on Firefox avif is used and on safari jpg is used as fallback.
codesandbox
As MDN usage examples there's no inbuilt fallback for image-set(), therefore putting an background-image before.
.box {
background-image: url("large-balloons.jpg");
background-image: image-set(
"large-balloons.avif" type("image/avif"),
"large-balloons.jpg" type("image/jpeg")
);
}
also as you can see above the example uses type param, which safari doesn't support.
Another solution you can use is to have @media selectors specifically for safari and put specific code for this browser there: Media query for safari browser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With