StevoHN
StevoHN

Reputation: 481

How do I make a placeholder image in HTML if the original image hasn't been found?

Basically what the title says.

I'm making an html page, and using images for link. But can I make it so the images show a default icon if the specified file hasn't been found?

Upvotes: 21

Views: 132567

Answers (5)

ESP32
ESP32

Reputation: 8708

I have a solution without a background image and without JS. It uses a pseudo element in CSS. See it answered in this question: https://stackoverflow.com/a/57209608/3177115

Upvotes: 0

Fatimazahrae Jalal
Fatimazahrae Jalal

Reputation: 11

img {
  width:100px;
  height:100px;
  background: url(https://i0.wp.com/reviveyouthandfamily.org/wp-content/uploads/2016/11/house-placeholder.jpg?ssl=1) no-repeat scroll 0 0;
}
<img src="not-found.png" /><img src="https://i0.wp.com/reviveyouthandfamily.org/wp-content/uploads/2016/11/house-placeholder.jpg?ssl=1" />

Upvotes: 1

Swaps
Swaps

Reputation: 1548

If you just want to display a blank space without any dummy image/caption, remove the alt option that you have specified in the img tag.

<img src='not_found.jpg' alt='' class=''>

Here the source not_found.jpg is the wrong path which won't give any image. PFA for sample o/p.

  • Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.

Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.

Upvotes: 2

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

If you specify the width and height of an image in the css, you can set the background image as a not-found image:

img {
  width:100px;
  height:100px;
  background: url(http://goo.gl/vyAs27) no-repeat scroll 0 0;
}
<img src="not-found.png" /><img src="http://goo.gl/ijai22" />

Most browsers will insert an image missing icon in the corner. There's no way that I know of to remove this.

As you can see, your regular image will overlay the background image.

If your image has a transparent background then the background image will be visible behind the loaded image.

Alternatively, use a server-side programming language that checks if the image exists. If it does not, load a placeholder...

Upvotes: 21

x13
x13

Reputation: 2227

You'll have to use javascript:

<img src="404image" onerror="this.src='images/not_found.png';" />

Upvotes: 53

Related Questions