I want to set an image as a background, however the image name might be either bg.png
or bg.jpg
.
Is there any non-javascript way to create a fallback to an alternative image if the default background doesn't exist?
body{
background: url(bg.png);
background-size: 100% 100%;
width: 100vw;
height: 100vh;
margin: 0;
}
To specify multiple possible backgrounds, you could do:
This will set the background to
bg.png
if it exists. If it doesn't exist, it will be set tobg.jpg
. If none of those images exist, the background will be set to the staticgreen
color.Note that it will prioritize whatever image is specified first. So if both images exist, it will choose the
bg.png
over thebg.jpg
.Check out the demo here. Test it by breaking any of the image urls'.
I wanted to have a solution that doesn't load the images twice. For example CDN with a fallback is not very good if it always loads the original images also. So I ended up writing a Javascript to manipulate the loaded CSS DOM.
You can use multiple backgrounds if there is no transparency involved and they occupy all available space or have the same size:
If the first doesn't exit, the second will be displayed.