简体   繁体   English

如何在 sass 中使用 WebP

[英]How to use WebP in sass

In my scss file I have:在我的 scss 文件中,我有:

.banner{
    background-image: url("/images/image.jpg");
}

Now I've converted this to a WebP image.现在我已将其转换为 WebP 图像。 I know that if it were an image inside html I should do:我知道如果它是 html 中的图像,我应该这样做:

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

However, how to do something similar in a sass SCSS file?但是,如何在 sass SCSS 文件中执行类似的操作? (I'm using Reactjs) (我正在使用 Reactjs)

There's no way to detect webp support with CSS.无法使用 CSS 检测 webp 支持。

The best you are likely to be able to achieve is to use JavaScript to detect support and add a class to an element (eg with modernizr ).您可能能够实现的最佳效果是使用 JavaScript 来检测支持并将 class 添加到元素(例如使用modernizr )。 Since the body element is usually outside the scope of the elements modified by React, adding the class there with modernizr shouldn't be a problem.由于body元素通常位于 React 修改的元素的 scope 之外,因此使用modernizr 添加 class 应该不是问题。

Then you can use that class to pick which rule to use:然后您可以使用该 class 来选择要使用的规则:

.banner{
    background-image: url("/images/image.jpg");
}

.webp .banner{
    background-image: url("/images/image.webp");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM