How to create a preloader with CSS?


A preloader as the name suggests loads when the web page is loaded. Consider it as a loading page or a loading screen before the content on the web page is visible. With CSS, we can easily create a preloader and can also style it using the border properties. The animation for the loader is set with keyframes.

Style the loader

To style the loader, the border properties are used. The height and width are also set −

.loader {
   border: 16px double #ffee00;
   border-radius: 50%;
   border-top: 16px solid #7434db;
   width: 140px;
   height: 140px;
   -webkit-animation: loader 2s linear infinite; /* Safari */
   animation: loader 2s linear infinite;
}

Animate the loader infinite

To animate the loader, we have used the animation property. It is also set the Safari web browser. The name of the animation is set to loader. For spinning it forever, infinite animation is set. We have used the shorthand animation property below. The spinning is set with animation-iteration-count if the shorthand property is not used −

webkit-animation: loader 2s linear infinite; /* Safari */
animation: loader 2s linear infinite;

Set the loader animation

The rotation for the animation is set using the rotate() method. Under that, the degree of rotation is set. The rotate() is set using the CSS transform property −

For 0%, the degree is set to 0 degrees, whereas for 100%, the degree is set 360 degrees −

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

The loader animation for unsupported web rbwoser

The -webkit- prefix is used for the web browsers that do not support animation and transform properties −

@-webkit-keyframes loader {
   0% {
      -webkit-transform: rotate(0deg);
   }
   100% {
      -webkit-transform: rotate(360deg);
   }
}

Example

To create a preloader with CSS, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <style>
      body{
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }
      .loader {
         border: 16px double #ffee00;
         border-radius: 50%;
         border-top: 16px solid #7434db;
         width: 140px;
         height: 140px;
         -webkit-animation: loader 2s linear infinite; /* Safari */
         animation: loader 2s linear infinite;
      }
      @-webkit-keyframes loader {
         0% {
            -webkit-transform: rotate(0deg);
         }
         100% {
            -webkit-transform: rotate(360deg);
         }
      }
      @keyframes loader {
         0% {
            transform: rotate(0deg);
         }
         100% {
            transform: rotate(360deg);
         }
      }
   </style>
</head>
<body>
   <h1>Creating a pre Loader example</h1>
   <div class="loader"></div>
</body>
</html>

Updated on: 08-Dec-2023

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements