6

I want try to use images in WebP format as background images on my webpages. But I'm not sure, how make condition in CSS that if browser not support WebP format so in this case use classic jpg image. I find this example code, bud it doesn't work

.mybackgroundimage {
    background-image: url("image.jpg");
    background-image: image("image.webp" format('webp'), "image.jpg");
}
Petr Šrámek
  • 435
  • 7
  • 26
  • The above CSS are feature in CSS4 which browser support is unknown. http://www.w3.org/TR/css4-images/#image-fallbacks – Dennis C Sep 24 '13 at 09:11

1 Answers1

8

You must use modernizr to detect whether browser support webp or not and then apply appropriate style to it

.no-webp .mybackgroundimage 
{
background: url('image.jpg') no-repeat;

}

.webp .mybackgroundimage
{
background: url('image.webp') no-repeat;

}
Soheil Ghahremani
  • 1,135
  • 1
  • 16
  • 36
  • 9
    Its 2016! Is this still the only way to do in CSS3? – Gaurav Agarwal Feb 18 '16 at 22:27
  • If by any change anyone wanna use webp images as background-image css there is a support which I found today. Here is the code. // Input .banner{ background: url(/img/bannerbg.jpg) no-repeat center; } // Output .banner{ background: url(/img/bannerbg.jpg) no-repeat center; } @supports (-webkit-appearance:none){ .banner { background-image: url(/img/bannerbg.webp); } } – Harden Rahul Oct 26 '17 at 07:14
  • @HardenRahul Firefox follows Microsoft Edge: adds `-webkit-` prefixes – Andrei Krasutski Oct 28 '17 at 19:13
  • @HardenRahul, that doesn't work in Safari though. – Vince Mar 06 '20 at 18:09