netdjw
netdjw

Reputation: 5997

How to show .webp in Chrome and .jpg in Firefox or IE/Edge?

Is there any working example to show .webp format file in Chrome and a different .jpg format file in Firefox and IE / Edge?

I user now this CSS code:

#bgbox {
    background-imgage: url('../img/bg.webp');
}

Is there a -moz-background-image or something like this?

Upvotes: 2

Views: 12624

Answers (2)

Pawan
Pawan

Reputation: 3864

You can use image-set as well like for example:

#bgbox {
   background-image: url('https://www.gstatic.com/webp/gallery/4.jpg');
   background-image: -webkit-image-set(url('http://www.gstatic.com/webp/gallery/4.webp')1x );
}

so browser not supporting image-set or webp will use the default background-image. so you won't need any javascript like modernizr

Upvotes: 12

Valentin
Valentin

Reputation: 2858

The easiest way is to use a <picture> element and set a webp source with a jpg fallback. You can have multiple sources and the browser will try to load the first compatible one or use the fallback if none work.

<picture>
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" />
</picture>

If you need to set a background however a different approach is needed. You can use Modernizr to detect if the browser supports webp and apply different styles based on that.

.image {
  background-size: cover;
  width: 100px;
  height: 100px;
}

.no-webp .image {
  background-image: url('https://www.gstatic.com/webp/gallery/4.jpg');
}

.webp .image {
  background-image: url('http://www.gstatic.com/webp/gallery/4.webp');
}
<script src="https://cdn.jsdelivr.net/modernizr/3.3.1/modernizr.min.js"></script>
<div class="image"></div>

Upvotes: 13

Related Questions