2017-07-10 3 views
1

J'ai actuellement le code CSS suivant que j'applique à un élément div qui affiche une image réactive.Affichage du chargement de l'image en utilisant CSS

.my-img-container { 
 
    position: relative; 
 
    &:before { 
 
    display: block; 
 
    content: " "; 
 
    background: url("https://lorempixel.com/300/160/") no-repeat; 
 
    background-size: 100% 100%; 
 
    width: 100% !important; 
 
    padding-top: 56.25%; 
 
    } 
 
    >img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100% !important; 
 
    height: 100% !important; 
 
    } 
 
}
<div class="my-img-container"> 
 
    <img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160"> 
 
</div>

Ce que je suis en train de faire est d'avoir un affichage d'image en arrière-plan pendant que l'image réactive chargement, d'où le content dans le CSS, mais il ne fonctionne pas. Une idée pourquoi?

Répondre

2

Vous pouvez définir la fileuse en arrière-plan à l'image:

html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
} 
 

 
img { 
 
    display: block; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    background: url(https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif) no-repeat center; 
 
}
<img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160">

4

Au lieu de charger une image plus petite pour montrer comme chargeur, il suffit de tourner un élément pseudo place.

Il a l'avantage de pouvoir démarrer beaucoup plus rapidement qu'une image et d'économiser un appel de serveur supplémentaire.

.my-img-container { 
 
    position: relative; 
 
    padding-top: 56.25%; 
 
} 
 
.my-img-container:before { 
 
    content: " "; 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    width: 80px; 
 
    height: 80px; 
 
    border: 2px solid red; 
 
    border-color: transparent red transparent red; 
 
    border-radius: 50%; 
 
    animation: loader 1s linear infinite; 
 
} 
 
.my-img-container > img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100% !important; 
 
    height: 100% !important; 
 
} 
 
@keyframes loader { 
 
    0% { 
 
    transform: translate(-50%,-50%) rotate(0deg); 
 
    } 
 
    100% { 
 
    transform: translate(-50%,-50%) rotate(360deg); 
 
    } 
 
}
<div class="my-img-container"> 
 
    <img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160"> 
 
</div>