Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display alternate image

Tags:

Is it possible to show an alternate image if the original source file is not found? I would like to achieve this only with css and html, no javascript (or jQuery and alike). The idea is to still show an image instead of the "alt" test or default (ugly) cross of IE. If not possible without javascript I will then rather check the img src with php with a basic if-then-else.

like image 849
rodedo Avatar asked May 27 '12 07:05

rodedo


2 Answers

Very simple and best way to achieve this with little code

<img class="avatar" src="img/one.jpg" alt="Not Found" onerror=this.src="img/undefined.jpg"> 

To me the above works perfect!

like image 156
Magige Daniel Avatar answered Oct 18 '22 19:10

Magige Daniel


You can do this using the CSS background-image property of the img element, i.e.

img { background-image:url('default.png'); } 

However, you have to give a width or height for this to work (when the img-src is not found):

img { background-image:url('default.png'); width:400px; } 
like image 24
emrea Avatar answered Oct 18 '22 21:10

emrea