:: before is not displayed in img

3

I created a sort of lazyload (preloading images) in JavaScript with the scroll event where some images only load when they enter the visible area of the window.

For this I created a generic image of 1x1 transparent pixel ( dt.png ) and placed in the src of the images and a data-src attribute with the path of the respective image:

<img src="dt.png" data-src="img/foto1.jpg" class="lazyload">
<img src="dt.png" data-src="img/foto2.jpg" class="lazyload">

When doing scroll , the JavaScript code will check if the image is inside the viewport window, if it will it will replace the value of src with data-src loading and displaying the image . So far so good.

The problem is that I wish there was not an empty area in the image's place, but that there was a text of type "Loading image ...", because sometimes the image takes a few seconds to load and gives the impression that there was some flaw. Anyway, I would like the user to know that the image will be displayed there.

I tried to do this using the ::before pseudo-class in the <img> tag and even works if the src is empty:

.lazyload::before{
   content: 'Carregando imagem...';
   position: absolute;
   right: 3px;
   top: 3px;
}

div{
   width: 300px;
   background: red;
   padding: 15px;
   color: white;
   text-align: center;
}

img{
   position: relative;
   width: 300px;
   height: 200px;
}
<div>
   <img src="" data-src="img/foto1.jpg" class="lazyload">
   <p>Texto qualquer</p>
</div>
  

But with src empty is not interesting because it shows the "   image start "as well as a border.

Now with transparent PNG, the text of ::before does not appear (even if the PNG is transparent):

.lazyload::before{
   content: 'Carregando imagem...';
   position: absolute;
   right: 3px;
   top: 3px;
}

div{
   width: 300px;
   background: red;
   padding: 15px;
   color: white;
   text-align: center;
}

img{
   position: relative;
   width: 300px;
   height: 200px;
}
<div>
   <img src="https://i.stack.imgur.com/Qk53m.png"data-src="img/foto1.jpg" class="lazyload">
   <p>Tem uma imagem transparante aqui em cima</p>
</div>
  

Looking at the element inspection of the browser, I noticed that when the    src is empty or with an image path that does not exist, the    ::before appears, but when I put a correct image path, the    ::before some.

Is there any way to make this ::before visible even with transparent PNG in src or another possible solution for this case using CSS?

    
asked by anonymous 29.09.2018 / 20:36

1 answer

3

It does not make sense to use the pseudoelement ::before with <img> , since this tag has no content (it has no closing tag). Despite the confusing name, ::before creates a pseudo-element before content of the element specified in the selector (that is, in the position of the first child), not before the element itself is selected.

In practical terms, place the pseudo-element in an element external to the image.

    
29.09.2018 / 23:17