Andrey Lechev
Index Of /

Index Of /

Using AVIF as a background image

Well, you probably already heard that AVIF has landed. If not, click on the link and read. But there is a problem with all these new file formats. Despite their support by the element, when you want to use it as a background image — you don't have a way to tell which URL is for which browser.

When I was working a lot on the image optimizations, I was using a simple script that checks if the browser can render a specific type of image and sets the corresponding class to the element. The script is available on my GitHub:

And today I have added support for the AVIF files. And updated the usage instructions like this:

/* Browser supports AVIF */ 
.avif .myelem { 
  background-image: url('myimage.avif'); 

/* Browser does not support AVIF, but supports WebP */ 
.webp.notavif .myelem { 
  background-image: url('myimage.webp'); 

/* Browser does not support AVIF nor WebP and gets JPEG */ 
.notavif.notwebp .myelem { 
  background-image: url('myimage.jpg'); 

So go and grab the script and use AVIF everywhere you need.

Share this