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?
If you already use WebP images for your HTML <img> tags and want to enable WebP for the CSS background as well, the proper way is to use multiple backgrounds in the CSS styling. In this case, all browsers will get WebP images, except for ones that do not support WebP.
Using WebP in HTMLYou can use a WebP image in a normal <img> tag, but in browsers that without WebP support the image would be broken. In the code above we have different image versions in both WebP and JPEG to support high-res displays with 2x pixel density as well as dark mode.
According to caniuse, currently 79.2% of browsers support the WebP image format. That would include Chrome, Firefox, and Edge. Safari will support WebP in version 14, which is expected to be released in September 2020.
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) }
}
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"));
}
Doku
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With