Use image sets to implement fallback background images without relying on javascript
P粉523335026
P粉523335026 2024-03-30 11:00:34
0
1
353

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粉523335026
P粉523335026

reply all(1)
P粉579008412
background-image: url("/static/img/image.avif"),url("/static/img/image.avif") 1x,url("/static/img/image.png") 1x;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!