How do I create a CSS-only animated loading spinner?
Rashid D
rashid d profile pic

Creating a CSS-only animated loading spinner involves using CSS keyframe animations to rotate an element continuously. Here's a step-by-step explanation of how you can create a CSS-only loading spinner: HTML Markup: Start by creating the HTML structure for your loading spinner.

1
div class="spinner"></div>

CSS Styling: Apply the following CSS styles to create the animated loading spinner:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

In this example, the.spinner class represents the element that will display the loading spinner. Adjust thewidth,height, andborder properties to control the size and appearance of the spinner. Theborder-radius property is set to50% to make the spinner circular. Theborder property sets the thickness and color of the spinner's outer border, while theborder-top property defines the thickness and color of the top border, creating the spinning effect. Theanimation property is used to apply thespin animation to the spinner. Thespin animation is defined using the@keyframes rule, which specifies the rotation of the spinner from0deg to360deg over a duration of1s. Thelinear timing function ensures a smooth and consistent rotation. By applying these CSS styles, the loading spinner will appear as a circular shape with a spinning animation. The spinner will continuously rotate, creating the illusion of a loading animation. You can customize the size, colors, animation duration, and other aspects of the spinner to match your design requirements. Additionally, you can combine the spinner with other CSS techniques, such as transitions or opacity animations, to create more complex loading effects. Remember to consider accessibility by providing alternative text or visual cues to indicate that content is loading.