How to Create a Loading Spinner in CSS with Overlay.

How to Create a Loading Spinner in CSS with Overlay.

Timonwa Akintokun Timonwa Akintokun

2 min read


CSS Loading Spinner with Overlay
CSS Loading Spinner with Overlay

Code

<div class="loading"></div>
.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);
  }
}

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>
.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);
  }
}

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

If this article helped you, it might help someone else too. Click the share button below to spread the word!
Got thoughts or questions? Lets connect on X or LinkedIn.
Till next time, happy coding! 😊

Man waving goodbye


Enjoyed this article?

Be the first to get new blog posts, tutorials, and developer productivity tips delivered to your inbox.

More posts in web development