I am trying to use webp images throughout my site due to the better compression. However I am aware that safari does not support webp. The images are loaded using background-image: url("img/img.webp)
. I then apply other background
properties.
I understand the <picture>
tag can be used to show different images depending on browser support. Like so.
<picture>
<source srcset="some_img.webp" type="image/webp">
<img src="some_img.jpg"alt="">
</picture>
However it would be much more convenient if there was a way to do it using css to save me having to write new html and styling for all the images.
For instance something like this
#image-id {
background-image: url("../img/img.webp", "../img/img.jpeg"); // show jpeg if webp not supported
}
Or if that is not possible then maybe something like this
@media only screen and (safari-specific-property:) {
background-image: url("../img/img.jpeg"); // show jpeg for safari
}
What is the best solution for using webp images while maintaining browser support, which ideally uses css?
interesting questing here. As far as I know you could use either the cascade or @supports.
Let's see what happens when we use cascade:
.bg {
/*fallback */
background-image: url("https://www.gstatic.com/webp/gallery/2.jpg")
background-image: url("https://www.gstatic.com/webp/gallery/1.webp");
}
It'll work fine but browsers that understand JPG and WebP (which are the majority) will make two requests, and that's not optimal.
Now, let's have a look to the @supports at rule.
@supports not (background-image: url("https://www.gstatic.com/webp/gallery/1.webp")) {
.bg {
background-image: url("https://www.gstatic.com/webp/gallery/2.jpg")
}
}
.bg {
background-image: url("https://www.gstatic.com/webp/gallery/1.webp");
}
Since the majority of browsers supports WebP I think this solution is ideal.
Browsers that don't support WebP will fall into the at-rule getting the JPG. Then they will read the next style that calls a WebP and since they don't support that feature they just will stick with the JPG. I'd like to know if you could try this in a safari browser.
Links of interest:
https://css-tricks.com/how-supports-works/
https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/
The final answer would be this:
@supports not (background-image: url("https://www.gstatic.com/webp/gallery/1.webp")) {
.bg {
background-image: url("https://www.gstatic.com/webp/gallery/2.jpg")
}
}
@supports (background-image: url("https://www.gstatic.com/webp/gallery/1.webp")) {
.bg {
background-image: url("https://www.gstatic.com/webp/gallery/1.webp")
}
}
Because if you only put one @support query, the browser will download the other one that is not surounded with @support. This way the browser will only load one background-image: The one that fits better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With