6

I refactored my app with avif format for phone devices (even if it's not supported everywhere).

This code works perfectly, it prioritize avif format if it's supported by the browser:

<picture>
   <source srcset="image.avif" media="(max-width:500px)" type="image/avif" />
   <img src="image.jpg" alt="nice dog" />
</picture>

But I also got some images as background-image css property. I tried the image-set property but without success.

div {
  background-image: -webkit-image-set(
        url('image.avif') type("image/avif"),
        url('image.jpg') type("image/jpeg"));
  background-image: image-set(
        url('image.avif') type("image/avif"),
        url('image.jpg') type("image/jpeg"));
}

I looked at the example 2 here. Even Firefox nor chrome doesn't interpret well this code. Any idea ? Am I trying something that is still in draft for browsers ?

PestoP
  • 247
  • 2
  • 11

1 Answers1

8

You had the right clue. The image-set property does not yet support the type declaration. This is currently part of the CSS4 draft version which you also linked: https://drafts.csswg.org/css-images-4/

For right now, I am simply converting my images to AVIF with https://avif.io/ and use a detection script to add an "avif" class into my HTML. Then it's as simple as:

.image {background-image:url("image.jpg")}
.webp .image {background-image:url("image.webp")}
.avif .image {background-image:url("image.avif")}

There are several types of detection scripts:

Another hacky way would be to make a media query for the content-visibility feature, as it launched with the same versions that AVIF support in Chrome and Opera was released. However I wouldn't rely on that on a production app.

Hope this helped you out. :)