How to specify an alternate image in CSS background-image property if WebP format is not supported by browser

Viewed 582

I have an a element with background image

        <div class="col-sm-6 col-lg-4"><a class="thumbnail" href="~/home/products"
              style="background-image: url(/../images/image-370x370.jpg)">
                  <div class="thumbnail-caption">
                    <h3 class="thumbnail-heading">E-Commerce</h3>
                    <div class="thumbnail-inner">
                      <div class="thumbnail-content">
                        this is a complete e-commerce solution through which you can manage your online store.
                      </div>
                      <div class="thumbnail-icon fa-angle-right"></div>
                    </div>
                  </div></a>
        </div>

In the second line style="background-image: url(/../images/image-370x370.jpg)" I want to use the WebP format image with css background-image to reduce the size of request and specify the alternate image if WebP is not supported.

As we can do this with picture element:

<picture>
  <source type="image/webp" srcset="flower.webp">
  <source type="image/jpeg" srcset="flower.jpg">
  <img src="flower.jpg" alt="">
</picture>
2 Answers

What about using << background-image: "image-set" >> like:

style='background-image: url("/../images/image-370x370.jpg");
       background-image: image-set("/../images/image-370x370.webp", "/../images/image-370x370.jpg");
       background-image: -webkit-image-set("/../images/image-370x370.webp", "/../images/image-370x370.jpg");'

That worked for me.

You can use multiple images:

style="background-image: url(/../images/image-370x370.webp),
                         url(/../images/image-370x370.jpg)"
Related