【问题标题】:How to specify an alternate image in CSS background-image property if WebP format is not supported by browser如果浏览器不支持 WebP 格式,如何在 CSS 背景图像属性中指定备用图像
【发布时间】:2021-11-16 04:41:10
【问题描述】:

我有一个带有背景图片的元素

        <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>

在第二行 style="background-image: url(/../images/image-370x370.jpg)" 我想使用带有 css background-image 的 WebP 格式图像来减小请求的大小并在不支持 WebP 的情况下指定备用图像。

我们可以用图片元素来做到这一点:

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

【问题讨论】:

    标签: html css performance webp


    【解决方案1】:

    您可以使用多个图像:

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

    【讨论】:

    • 来自 MDN:背景图像是在相互叠加的上下文层上绘制的。指定的第一层被绘制为最接近用户。所以以上将无法达到预期的目的
    • 如果支持 webp,这将同时加载 webp 版本以及其他文件(jpg 版本)
    猜你喜欢
    • 2019-04-11
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2021-09-23
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多