Showing a representation of your UI while data is loading has become common practice and is the best way to make your site feel faster and less sluggish when loading your data.
There's a lot of Skeleton Loader libraries out there for frameworks like React, Vue and others, but they seem too large and complex for what they're trying to solve. In this post I'm going to show you how to create a simple skeleton loader in pure CSS and HTML.
We'll just use a single class and a CSS animation for this, which can be applied to any HTML element.
Let's stay off by defining class .skeleton
and adding our background gradient, which will be animated.
.skeleton {
background: linear-gradient(90deg, #ddda 40%, #efefefaa, #ddda 60%) right / 300% 100%;
}
The 90deg
is to turn our gradient from a vertical gradient to a horizontal gradient.
Now let's create our @keyframes
to use in our CSS animation, thankfully it's very simple.
@keyframes skeleton-loading {
to {
background-position: left;
}
}
This simply moves the background position to the left, which due to the way that our gradient is setup, will make the shiny part of the gradient look like it's moving towards the right.
Now let's add the keyframes as a CSS animation on the .skeleton
class, while we're at it let's also add a progress cursor, when hovering hover the elements with the cursor.
.skeleton {
cursor: progress;
background: linear-gradient(90deg, #ddda 40%, #efefefaa, #ddda 60%) right / 300% 100%;
animation: skeleton-loading 1.5s linear infinite;
}
The 1.5s
is the amount of time it takes for the glowing effect to move from the left to the right, in this case 1.5 seconds.
Now let's create our skeleton elements, since it's nothing but CSS, we can shape the skeleton loader however we'd like it. The GIF bellow is not showing the fine gradient that the linear-gradient
provides, but it's still a nice representation.
Below is a text element with the length of 100px
and the height of our text using em
units.
<div class="skeleton" style="width: 100px; height: 1em;"></div>
Now let's create an avatar loader or a loader for any other circle you might have in your UI.
<div class="skeleton" style="width: 100px; height: 100px; border-radius: 100%;"></div>
You might be running into issues where the skeleton isn't showing, simply adding a whitespace character will solve this and can be fixed with content
CSS property.
Let's go back to our .skeleton
class and add content
.skeleton {
content: ' ';
cursor: progress;
background: linear-gradient(90deg, #ddda 40%, #efefefaa, #ddda 60%) right / 300% 100%;
animation: skeleton-loading 1.5s linear infinite;
}
You should be all set now, hope it helped!