2017-11-02
CSS
Fun with Single-Element CSS Spinner
转载于 https://ariya.io/2017/10/fun-with-single-element-css-spinner
以下是原文

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:
00.square {
01    width: 64px;
02    height: 64px; 
03    border: 6px solid rgba(0, 0, 0, 0.1);
04}

00.circle {
01    border-radius: 50%;
02    width: 64px;
03    height: 64px;
04    border: 6px solid rgba(0, 0, 0, 0.1);
05}

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:
00.circle {
01    border-radius: 50%;
02    width: 64px;
03    height: 64px;
04    border: 6px solid rgba(0, 0, 0, 0.1);
05    border-top: 6px solid #555;
06}

Unsurprisingly, the rotating nature of a spinner can be easily achieved via CSS Animation. Now we just need to rotate this circle infinitely:
00@keyframes rotating {
01    100% {
02        transform: rotate(360deg);
03    }
04}
05
06.spinner {
07    border-radius: 50%;
08    width: 64px;
09    height: 64px;
10    border: 6px solid rgba(0, 0, 0, 0.1);
11    border-top: 6px solid #555;
12    animation: rotating 1.2s infinite linear;
13}

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:
00.spinner {
01    border-radius: 50%;
02    width: 64px;
03    height: 64px;
04    border: 6px solid rgba(0, 0, 0, 0.1);
05    border-top: 6px solid #555;
06    animation: rotating 1.2s infinite cubic-bezier(0.785, 0.135, 0.15, 0.86);
07}

Happy spinning!




回到顶部