Display alternate image

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

+6
source share
3 answers

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

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

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

 img { background-image:url('default.png'); width:400px; } 
+5
source
 <object data="foobar.png" width=200 height=200> <img src="test.png" alt="Just testing."> </object> 

Here foobar.png is the main image, test.png is the inverse image. According to the semantics of the object element, the content of the element (here the img element) should be displayed if and only if the primary data (specified by the data attribute) cannot be used.

Despite the fact that browsers had terrible errors in object implementations last year, this simple method works in modern versions of IE, Firefox, and Chrome.

+6
source

A very simple and best way to achieve this with a little code.

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

For me, this works great!

+4
source

Source: https://habr.com/ru/post/916776/


All Articles