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

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.

<img src="https://stackoverflow.com/questions/22051573/Error.src" onerror="this.style.display='none'"/>

or

<img src="https://stackoverflow.com/questions/22051573/Error.src" onerror="this.src="fallback-img.jpg""/>

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';};
   })
});
<img src="https://stackoverflow.com/questions/22051573/error.src">
<img src="https://stackoverflow.com/questions/22051573/error.src">
<img src="https://stackoverflow.com/questions/22051573/error.src">
<img src="https://stackoverflow.com/questions/22051573/error.src">

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.

Leave a Comment