How to hide image broken Icon using only CSS/HTML?

前端 未结 17 1804
不思量自难忘°
不思量自难忘° 2020-11-27 09:14

How can I hide the broken image icon? Example: \"Example\"

I have an image with error src:

17条回答
  •  醉话见心
    2020-11-27 09:50

    There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

    But here is a minimal method for either hiding the image, or replacing the source with a backup.

    
    

    or

    
    

    Update

    You can apply this logic to multiple images at once by doing something like this:

    document.addEventListener("DOMContentLoaded", function(event) {
       document.querySelectorAll('img').forEach(function(img){
      	img.onerror = function(){this.style.display='none';};
       })
    });
    
    
    
    

    Update 2

    For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

提交回复
热议问题