šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


4 Replies

  • Great article! I was having this exact problem on our magento site and was able to quickly fix it using the @supports option for the background images.

    • The purpose to use modern file formats. In this example you would like to use a webp image, because it has smaller file size (reduced page load, etc…). On the other hand you also want to provide jpeg for the older browsers.
      Finally your browser won’t load both files! (modern browser loads the webp image, old one falls back to the jpeg image)

    • I just tested this in Chrome and Safari. If webp is supported the browser does not download the jpeg. Try it yourself before complaining ^__^

Leave a Reply

Your email address will not be published. Required fields are marked *