Search code examples
htmlcssreactjssasswebp

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)


Solution

  • 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 (e.g. 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");
    }