问题
How do you detect in CSS if webp images are supported?
.home-banner-background {
background-image: url('img/banner.jpg');
}
/*Here is an if statement that will check if webp is supported*/ {
.home-banner-background {
background-image: url('img/banner.webp');
}
}
Is there an "if" statement which can do that?
回答1:
You can use Modernizr. It is a tool that detect available features on the user's browser. It is just a script to add in your website, and with it, you can write something like that :
.no-webp .home-banner-background {
background-image: url('img/banner.jpg');
}
.webp .home-banner-background {
background-image: url('img/banner.webp');
}
回答2:
This is currently not supported with CSS.
In the CSS Images Module Level 4 Draft, a fallback solution is suggested, but this is currently not supported anywhere. (2.4. Image Fallbacks and Annotations: the image() notation)
But if it will become part of a standard in some years, you then might be able to write:
.home-banner-background {
image:image('img/banner.webp', 'img/banner.jpg')
}
Until then you need to use tools like Modernizer, as suggested in the answer of Fifi
Alternatively, the picture
HTML tag might something you could think of, but if that is usable in your case depends on how the image should resize on your site:
<picture>
<source srcset="img/banner.webp" type="image/webp">
<source srcset="img/banner.jpg" type="image/jpeg">
<img src="img/banner.jpg">
</picture>
来源:https://stackoverflow.com/questions/57359223/how-to-detect-if-webp-images-are-supported-via-css