Home  >  Q&A  >  body text

Use image sets to implement fallback background images without relying on javascript

I'm fairly new to front-end and CSS. I'm trying to add background-image and load .avif files if they are supported. Otherwise fall back to the .png file. I'm wondering if it's possible to do this without javascript and without loading all the images without affecting page speed. I'm running Chrome 107.0.5304.110, ios 16.1 in (most) emulators (I know older versions of ios don't support avif, but the latest ones do. Would love to be able to use both at the same time ) and Firefox 106.0.1.

Attempt 1 Follow the previous answer. Note the usage of webkit-image-set. This is my code:

background-image: url("/static/img/image.png");
background-image: -webkit-image-set(url("/static/img/image.avif")1x );

This works in Chrome and Firefox, but Safari on ios shows a gray image.

Attempt 2 Follow the answers on this blog. Note that image-set is used here. 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 always shows png. I also reversed the position in the image set but got the same result. Always png.

Attempt 3, slightly different from Attempt 2. I just changed the format of 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 fine on chrome/firefox but is gray on ios.

Is there a way to solve this problem? Thanks!

P粉523335026P粉523335026183 days ago360

reply all(1)I'll reply

  • P粉579008412

    P粉5790084122024-03-31 09:46:17

    background-image: url("/static/img/image.avif"),url("/static/img/image.avif") 1x,url("/static/img/image.png") 1x;

    reply
    0
  • Cancelreply