简体   繁体   中英

How to use WebP in sass

In my scss file I have:

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

Now I've converted this to a WebP image. I know that if it were an image inside html I should do:

<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? (I'm using Reactjs)

There's no way to detect webp support with CSS.

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

Then you can use that class to pick which rule to use:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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