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.
For example, you have an element with .png CSS background:
.minicart-wrapper .action.showcart.desktop .fa-shopping-cart:before {
background: url(../images/icon-cart.png) no-repeat;
}
To switch it to the WebP, you need to convert PNG/JPG/GIF image to WebP image manually using one of the free tools on the Internet. Save it in the same folder and use CSS like this:
body.webp-supported
.minicart-wrapper .action.showcart.desktop .fa-shopping-cart:before {
background: url(../images/icon-cart.webp) no-repeat;
}
body.no-webp .minicart-wrapper .action.showcart.desktop .fa-shopping-cart:before {
background: url(../images/icon-cart.png) no-repeat;
}
In this case, all browsers will get WebP images, except for ones that do not support WebP. They will load the .png image.
Note: if you use Magento 2 with Magento 2 WebP Image extension "no-webp" & "webp-supported
" classes will be added to the <body> tag automatically and will be available for you out of the box.
In case you use some other platform or extension, then you need to integrate JavaScript (e.g. Modernizr), which can detect WebP in order to programmatically add no-webp, webp-supported classes to your body tag.