DEV Community

Cover image for How to Create a CSS Only Loading Spinner πŸ’«πŸ”₯
Dom (dcode)
Dom (dcode)

Posted on

How to Create a CSS Only Loading Spinner πŸ’«πŸ”₯

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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:

Alt Text

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
murkrage profile image
Mike Ekkel

I absolutely love pure CSS solutions like this. It’s short and simple, but so very effective.

Collapse
 
thomasbnt profile image
Thomas Bnt β˜•

Pretty cool and great post πŸ‘πŸ˜„

Collapse
 
ziizium profile image
Habdul Hazeez

Some comments may only be visible to logged-in visitors. Sign in to view all comments.