How to make a style for "broken image" (when the image does not load)

6

How would it be possible to make a CSS style for when the image is not loaded on the page?

When you have the link to the image, but for some reason it is not loaded on the page, or if the link or image path is wrong, or if the image is not in the correct folder or server, to create a CSS style to handle these broken images?

The normal thing to see is when the image does not load:

ButI'dlikesomethingmorecustomwithCSSlikethis:

    
asked by anonymous 09.08.2018 / 14:53

3 answers

6

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.

    
09.08.2018 / 15:00
3

Based on the bitsofcode solution: link

img {
  font-family: 'Helvetica';
  font-weight: 300;
  line-height: 2;  
  text-align: center;
  
  width: 100%;
  height: auto;
  display: block;
  position: relative;
  min-height: 50px;
}
/*
:before pode ser cobrido pela imagem, mas quando a imagem está quebrada ele fica visível
*/
img:before { 
  content: " ";
  display: block;

  position: absolute;
  top: -10px;
  left: 0;
  height: calc(100% + 10px);
  width: 100%;
  background-color: rgb(230, 230, 230);
  border: 2px dotted rgb(200, 200, 200);
  border-radius: 5px;
}
/*
:after mesmo comportamento de :before em relação à imagem
*/
img:after { 
  /* \f127 e a imagem de um link, do FontAwesome
     attr() pega um atributo do elemento, aqui pegando o "alt"
  */
  content: "\f127" " Imagem quebrada: '"  attr(alt) "'";
  display: block;
  font-size: 16px;
  font-style: normal;
  font-family: FontAwesome;
  color: rgb(100, 100, 100);
  
  position: absolute;
  top: 5px;
  left: 0;
  width: 100%;
  text-align: center;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

<img src="image-que-nao-existe.jgp" alt="alguma imagem" />

I've added some basic comments only and one minimal change. In the original link in English, there is an explanation of the use of :before and :after , in free translation:

  

The <img> element is a superseded element. This is an element "whose   appearance, and dimensions are defined by an external resource "   (Sitepoint). As the element is controlled by an external source, the   pseudo-elements :before and :after normally should not work   with him. However, when the image is broken and is not loaded,   these pseudo-elements may appear.

EDIT taking advantage of @Guilherme's suggestion, I tested it in browsers:
- It worked on Chrome 68, Chrome on Android, Firefox 61 and Opera 36 (old middle)
- It did not work on IE 9/11, Edge got weird

    
09.08.2018 / 16:39
1

I used any CSS but you put yours.

Pure JavaScript

  

In event onerror (which fires if an error occurs while loading the image) call a function to change the content of div that contains the image

Example 1

function img_erro(){
   var element = document.getElementById("trap_section");
   element.innerHTML = '<div id="trap_top1" style=""></div><div id="section1"><div class="indent"><div><h1>Erro ao carregar imagem</h1><p>Deu ruim</p></div></div></div><div id="trap_bottom1" style=""></div>';
}
            .trap_section{
                position: relative;
                width: 500px;
                border: none;
                margin-top: 100px;
            }
            #trap_top1{
                position: absolute;
                top: -80px;
                border-top: 80px solid transparent;
                border-right-width: 500px; border-right-style: solid; border-right-color: rgb(255, 137, 91);
            }
            #trap_bottom1{    
                position: absolute;
                bottom: -80px;
                border-bottom: 80px solid transparent;
                border-right-width: 500px; border-right-style: solid; border-right-color: rgb(255, 137, 91);
            }
            #section1{
                background: #FF895B;
                color: #FFFFFF;
                margin: 0 auto;
                overflow-y: hidden;
                height: 200px;
            }
            h1, p{text-align:center;}
 
 <div id="trap_section" class="trap_section">
      <img src="sem_url" onerror="img_erro()">
 </div>

Example 2

function myFunction() {
    document.getElementById("myDIV").className = "mystyle";
    document.getElementById("myDIV").innerHTML = 'Erro ao carregar imagem';
}
.mystyle {
    width: 300px;
    height: 50px;
    background-color: gray;
    text-align: center;
    font-size: 25px;
    color: white;
    margin-bottom: 10px;
}
<div id="myDIV">
<img src="image.gif" onerror="myFunction()">
</div>

For those who already use Jquery:

  

Use the jQuery error event and do whatever action you want if the image can not be loaded.

  • Hide the tag image $(this).hide();
  • Add content instead $( "#id_div").append(...

        
$("#img").on("error", function() {
    $(this).hide();
    $( "#id_div").append( '<div class="trap_section"><div id="trap_top1" style=""></div><div id="section1"><div class="indent"><div><h1>Erro ao carregar imagem</h1><p>Deu ruim</p></div></div></div><div id="trap_bottom1" style=""></div>');
});
    .trap_section{
                    position: relative;
                    width: 500px;
                    border: none;
                    margin-top: 100px;
                }
                #trap_top1{
                    position: absolute;
                    top: -80px;
                    border-top: 80px solid transparent;
                    border-right-width: 500px; border-right-style: solid; border-right-color: rgb(255, 137, 91);
                }
                #trap_bottom1{    
                    position: absolute;
                    bottom: -80px;
                    border-bottom: 80px solid transparent;
                    border-right-width: 500px; border-right-style: solid; border-right-color: rgb(255, 137, 91);
                }
                #section1{
                    background: #FF895B;
                    color: #FFFFFF;
                    margin: 0 auto;
                    overflow-y: hidden;
                    height: 200px;
                }
                h1, p{text-align:center;}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="id_div">
          <img id="img" src="semUrl">
        </div>

Using a default image

<!--imagem existente -->
<img src="https://i.stack.imgur.com/CF2nj.jpg?s=48&g=1"onerror="this.onerror=null;this.src='https://i.stack.imgur.com/Mf7KP.png';" />


<!--imagem sem src -->
<img src="semSrc" onerror="this.onerror=null;this.src='https://i.stack.imgur.com/Mf7KP.png';" />
    
09.08.2018 / 17:19