Well, I do not know if there is any way to resolve this just by CSS, but what I usually do is use the onerror
event to capture when there is a failure to open the image.
like this:
document.querySelector('img').addEventListener('error', function() {
// sua lógica aqui.
})
It is common to set another src
for the image, but you could also add a class to the image, or replace it with another element.
Example:
document.querySelector('.error').addEventListener('error', function () {
var div = document.createElement('div');
div.classList.add('img-error');
div.innerText = 'Imagem falhou';
this.replaceWith(div)
})
.img-error{
background-color: #ccc;
width: 100px;
height: 100px;
display: inline-flex;
justify-contents: center;
align-items: center;
}
<img src="https://i.stack.imgur.com/CF2nj.jpg?s=48&g=1"><imgsrc="nao_existe" class="error">
Note : If you choose to change the src
of the image to onerror
, make sure that the fallback image used to "plug the error" actually exists, otherwise this will cause a loop infinite in the call of onerror
(it happened to me when I forgot to publish an image that represented the user without a photo).
Option 2
Another thing I like to do is to use background-image
in a div
with predefined formatting (a background-color
for example). So when the image fails to load, background-color
will be there to do fallback.