I've been waiting to use .webp images for a very long time.
It's 2022, so, given:
- the image format has existed for a decade
- Chrome started supporting
.webpin Jan 2014 - Firefox started supporting
.webpin Jan 2019
I decided the day before yesterday to take the plunge and convert a bunch of .png images on a website to .webp images.
Rookie error. Because, of course, I should have checked: https://caniuse.com/webp first and that would have told me that Safari on anything earlier than macOS 11.0 Big Sur (Nov 2020) does not support .webp images.
But I'm tired of waiting. So... Safari can carry on using .png images I suppose.
Because I absolutely do want to serve .webp images to Firefox, Brave, Chrome, Edge, Opera etc. users.
If I were using marked up images, declaring one or more fallback images is elementary:
<picture>
<source srcset="a-webp-for-most-browsers.webp" type="image/webp">
<source srcset="a-png-for-safari.png" type="image/png">
<img src="a-png-for-safari.png" alt="My Image">
</picture>
But (sigh) in this instance, the images are CSS background images, so options for creating fallbacks are more limited:
- CSS
image-setstill has pretty low support at present - CSS feature queries using
@supportsdo not extend to image formats.
Am I limited to browser-sniffing via PHP, like this:
if (preg_match('/Mac OS X/', $_SERVER['HTTP_USER_AGENT'])) {
$Body_Element_CSS_Class_List .= ' oh-no-here-comes-safari';
}
Is there a better / more reliable approach I can adopt than browser-detection?
Yes, it's hard to provide fallbacks for CSS background-images
In my question I wrote:
And for now, at least, - ie. while we're still waiting (in 2022) for widespread cross-browser support for the CSS
image-set()function - that's true.But a marked-up
<img>can replace each CSS background-imageWhile I was hunting around for alternative approaches, I unexpectedly came across this July 2021 comment by Quentin Albert:
This was news to me. I was dimly aware of the
object-fitCSS property, but I'd never come across theobject-positionCSS property at all.But it absolutely works!!
The CSS I would have used if
image-set()had supportIf
image-set()had extensive cross-browser support, this was my intended CSS, which would enable a fallback image for Safari:The HTML + CSS I can use instead (thanks to
object-position)Since the above isn't close to reliable, I can declare the fallback image in HTML instead and position it using
object-position:HTML:
CSS: