DEV Community


Detect AVIF image support to use in your CSS

nucliweb profile image Joan León ・2 min read

AVIF is a next generation image format, in the moment to write this post, the support is only by Chrome 85 and Firefox 77 under a flag.

W3C are working in the CSS Images Module Level 4, and the new module will have an interesting feature, image-set and we'll can define the image type.

.element {
  background-image: image-set( "image.avif" type("image/avif"),
                               "image.webp" type("image/webp"),
                               "image.jpg" type("image/jpeg") );
Enter fullscreen mode Exit fullscreen mode

With image-set we'll can define different format and the browser render the first image format supported.

Until we have this awesome feature in the browsers, we can use JavaScript to detect the support, we'll to do a sample with the AVIF format.


body {
  background-color: #000;
  background-repeat: no-repeat;
  background-size: cover;
body.avif {
  background-image: url(./images/lions.avif);
} {
  background-image: url(./images/lions.jpg);
Enter fullscreen mode Exit fullscreen mode

I know that you can put the image in JPEG format directly in the body and overwrite the background-image if the browser supports it, but for the example I think it's clearer.

The JavaScript

async function supportsAvif() {
  if (!this.createImageBitmap) return false
  const avifData =
  const blob = await fetch(avifData).then((r) => r.blob())
  return createImageBitmap(blob).then(
    () => true,
    () => false
;(async () => {
  const classAvif = (await supportsAvif()) ? 'avif' : 'no-avif'
Enter fullscreen mode Exit fullscreen mode



I want to thank Jon Sneyers and Kornel, true magicians of image coders/decoders, for their help with the option of a base64 of an image of AVIF format as optimized as possible.


Editor guide