How to load image formats based on browser support using CSS?

Saj*_*rya 6 html css cross-browser background-image webp

I would like to use the WebP image format in my CSS background-image property. But, since WebP is quite new and still not supported by all browsers new and old, I would also like to add support for a JPEG version of that image as a fallback.

I know I can use the <picture> tag to do this like:

<picture>
    <source type="image/webp" srcset="image.webp">
    <source type="image/jpeg" srcset="image.jpg">
    <img src="image.jpg">
</picture>
Run Code Online (Sandbox Code Playgroud)

And this would make the browser load the first supported format. But can I achieve the same effect somehow using only CSS, since I am setting a background image using the background-image property? I know I can select images based on screen size using @media queries, but how do I load images based on browser support?

I have tried to search for a solution, but could not find one. Let me know if this is a duplicate and the solution already exists.

Thanks.

小智 -2

使用 2 张背景图片:一张为 JPG 或 PNG,另一张为 WEBP,浏览器会自动选择最佳的一张。

在 codepen 上找到此代码,作者:Robin Rendle

CSS:

element {
  width: 50vw;
  height: 100vh;
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/cust-housegreening-pup%402x-4cf7ada520811031a97bee12c06d9e9367f811bd86255ea60d40aa809cf58801.jpg');
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/cust-housegreening-pup@2x-4cf7ada520811031a97bee12c06d9e9367f811bd86255ea60d40aa809cf58801.webp');
}
Run Code Online (Sandbox Code Playgroud)

https://codepen.io/robinrendle/pen/ORmzJY

  • 我可以确认这种方法行不通。使用这种方法时,FireFox 和 Google Chrome 都会下载“.webp”版本的图像并且工作正常。但在不支持WebP的Safari(v12.1.1)上,这不起作用。Safari 仍然尝试下载 `.webp` 格式并且不显示图像。这是 CSS 的预期行为,因为当您使用多个“background-image”属性时,浏览器始终下载最后提到的图像。即使您提供的 codepen 也无法在 Safari 上运行。 (6认同)