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!
CodePudding user response:
It seem's that image-set
are partially supported on Safari browsers,
CodePudding user response:
background-image: url("/static/img/image.avif"),url("/static/img/image.avif") 1x,url("/static/img/image.png") 1x;