How to Specify Multiple Image Formats for a CSS "background-image"?

To enable browsers to automatically choose a suitable CSS background-image depending on supported formats (such as WebP and JPG for instance), you can use the CSS image-set() function. This function allows you to offer multiple image choices, and define their matching formats using the type() function:

background-image: image-set(
  url('image.webp') type('image/webp'),
  url('image.jpg') type('image/jpeg')
);

In the example above, using the image-set() and type() functions together allows the browser to choose the most appropriate image format based on its support. If the browser supports WebP, it will choose the "image.webp" option. Otherwise, it will use the "image.jpg" option.

If you wish to support browsers that do not support image-set(), you may have to add vendor prefixes and/or include a fallback before the "image-set()" declaration.

For example, you can add a fallback before the "image-set()" declaration in the following way:

.foo {
  background-image: url('image.jpg'); /* fallback for browsers that do not support `image-set()` */

  background-image: image-set(
    url('image.webp') type('image/webp'),
    url('image.jpg') type('image/jpeg')
  );
}

This ensures that browsers that do not support image-set() will still display the background image as expected.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.