tylerl
tylerl

Reputation: 1180

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?

Upvotes: 18

Views: 25722

Answers (4)

sidonaldson
sidonaldson

Reputation: 25284

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

Upvotes: 33

albert
albert

Reputation: 8153

Just declare the preferred default image after your background declaration:

.image
{
    background: #000 url('http://www.example.com/images/image1.png') 0 0 no-repeat;
    width: xxpx;
    height: xxpx;
    background-image: url('http://www.example.com/images/image1.png');
}

<span class="image"></span>

idk the dimensions of your img, so they are "xxpx" working demo: http://jsfiddle.net/jalbertbowdenii/rJWwW/1/

Upvotes: 1

BinderNews
BinderNews

Reputation: 560

Well, I know that the actual tag has onload, onerror, and onabort events. You could try loading it in an image, then if that succeeds, use JS to set the background property of the body.

EDIT: Never mind. I like his answer better.

Upvotes: 0

Matt Tew
Matt Tew

Reputation: 1621

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;}

Upvotes: 8

Related Questions