DEV Community

Cover image for How to Create a Loading Spinner in CSS with Overlay.
Timonwa Akintokun
Timonwa Akintokun

Posted on Edited on Originally published at tech.timonwa.com

How to Create a Loading Spinner in CSS with Overlay.

This article was originally published on Timonwa's Notes.

CSS Loading Spinner with Overlay
CSS Loading Spinner with Overlay

Code

<div class="loading"></div>
Enter fullscreen mode Exit fullscreen mode
.loading {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 10px solid #ddd;
  border-top-color: orange;
  animation: loading 1s linear infinite;
}
@keyframes loading {
  to {
    transform: rotate(360deg);
  }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

The loading spinner is a circle with a border. One part of the border is colored to stand out from the rest of the border. The spinner rotates using CSS animations.

  • The border property adds a border around the element to create the circle.
  • The border-radius property makes the border a circle.
  • We color one part of the border orange using the border-top-color property so that when the spinner rotates, the orange part stands out from the rest of the border, giving the illusion of a spinner.
  • The animation property is used to rotate the spinner.

Adding an overlay to the loading spinner

Adding an overlay to the loading spinner allows you to create a loading spinner that covers the entire page. This is useful when you want to show a loading spinner while a page is loading or when a form is submitting. This prevents the user from interacting with the page while the loading spinner shows.

If you want to add an overlay to the loading spinner, you can do so by wrapping it in a div and adding some styles.

<div class="loading-state">
  <div class="loading"></div>
</div>
Enter fullscreen mode Exit fullscreen mode
.loading-state {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}
.loading {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 10px solid #ddd;
  border-top-color: orange;
  animation: loading 1s linear infinite;
}
@keyframes loading {
  to {
    transform: rotate(360deg);
  }
}
Enter fullscreen mode Exit fullscreen mode

View the loading spinner on CodePen: https://codepen.io/timonwa/pen/dyaEVbp

Usage

Instances, where you might use a loading spinner, are

  • When a page is loading
  • When a form is submitting
  • When a component is loading

Top comments (0)