ariya.io About Collections Archives

Fun with Single-Element CSS Spinner

2 min read

There is no shortage of ready-to-use CSS-based loading spinners. Yet, it is still fun to derive a spinner from scratch, particular if the constraint is to use only one DOM element.

For this experiment, let us just focus on a round spinner. Just like the usual trick to make a round shape, it is a matter of setting the border radius of a square to be 50%, as illustrated here:

.square {
    width: 64px;
    height: 64px;
    border: 6px solid rgba(0, 0, 0, 0.1);
}
.circle {
    border-radius: 50%;
    width: 64px;
    height: 64px;
    border: 6px solid rgba(0, 0, 0, 0.1);
}

Obviously, for a spinner, it cannot be a solid uniform ring like that. What we ought to do is to color one side of the square differently, which is turned (with 50% border radius) into a dark arc in the circle:

.circle {
    border-radius: 50%;
    width: 64px;
    height: 64px;
    border: 6px solid rgba(0, 0, 0, 0.1);
    border-top: 6px solid #555;
}

Unsurprisingly, the rotating nature of a spinner can be easily achieved via CSS Animation. Now we just need to rotate this circle infinitely:

@keyframes rotating {
    100% {
        transform: rotate(360deg);
    }
}

.spinner {
    border-radius: 50%;
    width: 64px;
    height: 64px;
    border: 6px solid rgba(0, 0, 0, 0.1);
    border-top: 6px solid #555;
    animation: rotating 1.2s infinite linear;
}

As a final twist, there is no need to always use the linear timing function. For instance, for a more realistic effect, one can use a custom easing such as:

.spinner {
    border-radius: 50%;
    width: 64px;
    height: 64px;
    border: 6px solid rgba(0, 0, 0, 0.1);
    border-top: 6px solid #555;
    animation: rotating 1.2s infinite cubic-bezier(0.785, 0.135, 0.15, 0.86);
}

Happy spinning!

Related posts:

♡ this article? Explore more, check the archives, or follow me Twitter.

Share this on Twitter Facebook Google+

comments powered by Disqus