How to create a shaky loader with pure CSS

Effect preview

Online demo

Press the "click preview" button on the right to preview on the current page, and click the link to preview in full screen.
https://codepen.io/comehope/pen/oyJvpe

Interactive video

This video is interactive. You can pause the video at any time and edit the code in the video.

Please use chrome, safari, edge to open and watch.
https://scrimba.com/p/pEgDAM/cqwpQh7

Source code download

Download locally

Please download all the source code of the daily front-end combat series from github:
https://github.com/comehope/front-end-daily-challenges

Code interpretation

Define the dom. The container contains a child element with text in it:

<div class="loader">
    <span>Loading...</span>
</div>

Center:

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

Define container size:

.loader {
    width: 10em;
    height: 10em;
    font-size: 30px;
    box-sizing: border-box;
}

Set text style:

.loader span {
    position: absolute;
    color: white;
    width: inherit;
    height: inherit;
    text-align: center;
    line-height: 10em;
    font-family: sans-serif;
}

Draw the top arc that makes up the circle:

.loader {
    border-top: 0.3em solid hotpink;
    border-radius: 50%;
}

Draw another 2 arcs that make up the circle with pseudo elements:

.loader {
    position: relative;
}

.loader::before,
.loader::after {
    content: '';
    position: absolute;
    width: inherit;
    height: inherit;
    border-radius: 50%;
    box-sizing: border-box;
    top: -0.2em;
}

.loader::before {
    border-top: 0.3em solid dodgerblue;
    transform: rotate(120deg);
}

.loader::after {
    border-top: 0.3em solid gold;
    transform: rotate(240deg);
}

Define animation effects:

@keyframes rotating {
    50% {
        transform: rotate(calc(180deg * var(--direction)));
    }

    100% {
        transform: rotate(calc(360deg * var(--direction)));
    }
}

Apply animation to the circle:

.loader {
    animation: rotating 2s ease-in-out infinite;
    --direction: 1;
}

Apply animation to text:

.loader span {
    animation: rotating 2s linear infinite;
    --direction: -1;
}

Finally, hide what might go beyond the window:

body {
    overflow: hidden;
}

be accomplished!

Original address: https://segmentfault.com/a/119000015424389

Tags: Front-end github

Posted on Wed, 04 Dec 2019 18:09:58 -0500 by stevenszabo