Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

CSS Fallbacks for WebP background images with @supports

The WebP image type provides a big performance boost over the classic alternatives such as png's or jpeg's.

However, there are older browsers that don't support them.

Let's say we have the following CSS background-image declaration:

.logo-container {
    background-image: url('logo.webp');
}

We need to find a way to tell the browser something like: "use this WebP logo.webp image, and if you can't render it use this logo.jpeg alternative".

For this case, a great tool can be the CSS @supports rule.

Using @supports, we can test whether or not a browser supports a given declaration before using it.

.logo-container {
  background-image: url('logo.jpg');

  @supports (background-image: url('logo.webp')) {
    background-image: url('logo.webp');
  }
}

We are setting our default background image to a normal jpeg. Then, using @supports we can test if the browser can set the background image to the WebP version of the image. If so, it will overwrite the original jpeg.

And that's it!

By the way, in a previous article, we have also seen how to set a fallback background-image by using the multiple backgrounds CSS approach.

Home Screencasts Best of Newsletter Search X