'How to detect if webp images are supported via CSS
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?
Solution 1:[1]
The modern webkit browser will use the WebP background image with this CSS:
.map {background-image: url('../img/map.jpg');}
@supports (background-image: -webkit-image-set(url('../img/map.webp') 1x)) {
.map {background-image: -webkit-image-set(url('../img/map.webp') 1x) }
}
Solution 2:[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>
Solution 3:[3]
Use the type() function together with image-set() to provide alternative image formats with CSS.
In the example the type() function is used to serve the image in WEBP and JPEG formats. If the browser supports webp, it will choose that version. Otherwise it will use the jpeg version.
.box {
background-image: image-set(
url("large-balloons.webp") type("image/webp"),
url("large-balloons.jpg") type("image/jpeg"));
}
Solution 4:[4]
You could actually just add it to the original declaration without needing multiple classes, @supports, or bringing in another library similar to this:
.home-banner-background {
background-image: url('img/banner.jpg');
background-image: -webkit-image-set(url('img/banner.webp') 1x,
url('img/banner-2x.webp') 2x),
/* etc */;
}
Webkit will use the webp images and all others will fallback to the regular image.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
| Solution 2 | |
| Solution 3 | Take |
| Solution 4 | Poelinca Dorin |
