Displaying Loading Image using CSS

Sammy picture Sammy · Jul 10, 2017 · Viewed 7.4k times · Source

I currently have the following CSS code that I apply to a div element that displays a responsive image.

What I'm trying to do is have an image display in the background while the responsive image is loading, hence the content in the CSS, but it's not working. Any idea why?

Answer

Ason picture Ason · Jul 10, 2017

Instead of loading a smaller image to show as a loader, simply rotate a pseudo element instead.

It has the benefit of being able to start much faster than an image and save an extra server call.

.my-img-container {
  position: relative;
  padding-top: 50%;
}
.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 src="https://picsum.photos/600/300">
</div>