I currently have the following HTML code:
<header style="background-image:url(/images/header.webp)">
However, on some browsers (mainly older versions of Safari), webp is not supported. So I'd like to specify a fallback png image URL.
Using a picture
tag I can do something like:
<picture>
<source type="image/webp" srcset="/images/header.webp">
<source type="image/png" srcset="/images/header.png">
</picture>
How can I do the same thing using the background-image
CSS property?
Note, I can NOT use a CSS stylesheet for this, I must use the HTML style
attribute. This is due to how I'm dynamically generating the HTML content.
CodePudding user response:
CSS Tricks recommends using a feature detection library like Modernizr to add a class to the HTML root (like html.webp
) in supporting browsers, so you can write CSS that swaps a JPG or PNG image for a WEBP image:
.elementWithBackgroundImage {
background-image: url("image.png");
}
.webp .elementWithBackgroundImage {
background-image: url("image.webp");
}
CodePudding user response:
You can call multiple backgrounds. The second URL will act as a fallback if the browser can't find the first one.
<header style="background-image:url('/images/header.webp'), url('/images/header.png')">
Note: I am unsure whether the browser will opt to try and use the .webp even if it's unsupported. You should test this out to confirm.