Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if webp images are supported via CSS

Tags:

css

webp

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?

like image 492
Erez Shlomo Avatar asked Aug 05 '19 13:08

Erez Shlomo


People also ask

Does CSS support WebP?

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.

Does HTML accept 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.

Is WebP supported by all browsers 2021?

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.


2 Answers

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) }
  }
like image 131
glocsw Avatar answered Sep 28 '22 02:09

glocsw


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

like image 33
Take Avatar answered Sep 28 '22 04:09

Take