Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Extra background image for when the first image doesn't load?

Okay, let's say you have something like this:

<span class="image" style="background-image: url('http://www.example.com/images/image1.png')"></span>

Every CSS tutorial I've ever read has covered the concept of using a background color after the background-image code, which of course takes the place of the image when one is unavailable, but...

How do you specify a backup background-image - one that should be displayed if the image referenced is unavailable? If there's no CSS trick for this, maybe JavaScript could handle it?

like image 445
tylerl Avatar asked Oct 19 '11 05:10

tylerl


2 Answers

Simple answer:

You could either nest the span inside another span - with the outer span set to use the backup background image. If the inside span's background isn't available, then you'll see the outside one's

Better, more difficult answer:

You could achieve a similar result in pure CSS, by adding some psuedo content before the span, and then styling that to have the fallback background. However, this usually takes some trial and error to get it right;

Something lile

span.image:before{content:" "; background:url(backup.png); display: block; position:absolute;}
like image 26
Matt Tew Avatar answered Sep 20 '22 21:09

Matt Tew


In modern browsers you can chain background images and have more than one on each node. You can even chain background-position and background-repeat etc! This means you can declare your first image (which is the fallback) and then the second one appears over it, if it exists.

background-color: black;
background-image: url("https://via.placeholder.com/300x300?text=Top Image"), url("https://via.placeholder.com/300x300?text=Failed To Load");
background-position: 0 0, 0 0;
background-repeat: no-repeat, no-repeat;

JFIDDLE DEMO

like image 167
sidonaldson Avatar answered Sep 23 '22 21:09

sidonaldson