Give any HTML element a simple loading spinner with CSS

The ::after CSS selector allows you to add additional content to any HTML element. We can use this to give any HTML element an animated loading spinner.

A loading spinner is a one-coloured-side rotating square with a 50% border radius to make it look like a circle.

width: 20px;
height: 20px;
border: 2px solid #ccc;
border-top-color: blue;
border-radius: 50%;
box-sizing: border-box;

To place it in the center, we need to absolutely position it, make it start a 50% the width and height of the element, then move it back half its width and height (10px in our case).

position: absolute;
top: 50%;
left: 50%;
margin-top: -10px;
margin-left: -10px;

We need to add a CSS animation rule, spinner, to rotate it. Finally we add that as an linear infinite animation to our CSS class:

@keyframes spinner {
  to {transform: rotate(360deg);}
}
.spinner::after {
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-top-color: blue;
  border-radius: 50%;
  position: absolute; 
  top: 50%;
  left: 50%;
  margin-top: -10px;
  margin-left: -10px;
  animation: spinner .6s linear infinite;
  content: "";
}
.spinner {
  position: relative;
}

Note: .spinner has content: "" else the ::after selector won't show anything at all.

Note: the element needs to have position: relative so our spinner's position: absolute works, hence the final selector.

And our HTML button, or any other element, can be: <button class="spinner">loading</button>. And to remove the loading spinner remove the spinner class.



html css

Edit on github
comments powered by Disqus
Click me