DEV Community

Cover image for Creating a CSS Animated Loading Card
Chris Sev
Chris Sev

Posted on

Creating a CSS Animated Loading Card

Loading animations are used to tell users that the site they want to see is on the way. Usually we'll see spinners, but we can take this a step further.

Let's build out a card that has a loading animation to it. By creating a loading animation that looks similar to our final UI, the user will know what to expect when our page fully loads.

The steps to create an animated loading card are to:

  1. Create a card
  2. Add a background to specific parts (image, text)
  3. Animate with a CSS Animation

Here's the CodePen:

The Technique: Background Animation

We can build out a sample HTML/CSS card with the following:

<div class="card is-loading">
  <div class="image"></div>
  <div class="content">
    <h2></h2>
    <p></p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Using Sass, we can style out the base card:

.card {
  margin: 10px;
  width: 300px;
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);

  .content {
    padding: 20px 30px;
  }
}
Enter fullscreen mode Exit fullscreen mode

The CSS Loading Animation

Now we add a loading animation. This will be a CSS animation @keyframes that will move the background to give it a shining effect.

Here is the CSS animation:

@keyframes shine {
  to {
    background-position-x: -200%;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here is the is-loading class that will add the backgrounds to the image, header, and paragraph.

.card.is-loading {
  .image,
  h2,
  p {
    background: #eee;
    background: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%);
    border-radius: 5px;
    background-size: 200% 100%;
    animation: 1.5s shine linear infinite;
  }

  .image {
    height: 200px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
  }

  h2 {
    height: 30px;
  }

  p {
    height: 70px;
  }
}
Enter fullscreen mode Exit fullscreen mode

The important line here is the animation line:

animation: 1.5s shine linear infinite;
Enter fullscreen mode Exit fullscreen mode

We are animating the background infinitely so that the gradient keeps moving across the element.

Top comments (0)