How are good are loading spinners? I know I love them, so today we're going to build one using CSS. This is simple to do, and you can easily add them to your own web projects π
Video Tutorial
As always, if you prefer this tutorial in video form, feel free to watch it here, or on my YouTube channel dcode
The source code
If you want to follow along with the code, here you go:
Writing the HTML
For the HTML, we're going to add a sample <div>
which will act as the container for the loader. In a real-world application, this would be the space where your content goes once its loaded.
Inside the container, we have another <div>
which represents the actual loading spinner.
<div style="width: 150px; height: 150px;">
<div class="loading loading--full-height"></div>
</div>
And that's it for the HTML!
And now for CSS...
To achieve the spinning effect, we're going to be taking advantage of CSS animations and pseudo-elements.
First, we can style the .loading
class:
.loading {
display: flex;
justify-content: center;
}
We use display: flex
here so we can easily center the spinner horizontally and vertically.
Next, we take advantage of the :after
pseudo-element to represent the loader.
.loading::after {
content: "";
width: 50px;
height: 50px;
border: 10px solid #dddddd;
border-top-color: #009579;
border-radius: 50%;
animation: loading 1s ease infinite;
}
By using a top border (border-top-color
) in combination with a border-radius
of 50%
, we create a half-circle outline on the top of our pseudo-element, like this:
On the last line, we are specifying that the loading
animation gets applied to the spinner, and that it should run infinitely. Let's create that animation now.
@keyframes loading {
to {
transform: rotate(1turn);
}
}
And that's it! We have a very simple CSS only loading spinner. If you enjoyed this tutorial, check out my profile or YouTube Channel dcode for more π
Top comments (4)
I absolutely love pure CSS solutions like this. Itβs short and simple, but so very effective.
Pretty cool and great post ππ
Related:
My WebDev Notes: CSS loaders
Habdul Hazeez γ» Feb 25 '20 γ» 5 min read
Some comments may only be visible to logged-in visitors. Sign in to view all comments.