Loading animation with CSS
Here we are going to create spin loading animation with CSS animation property and HTML.
We normally use gif file for displaying loading animation. But here we will create spin loading animation with HTML and CSS only. We will not be using gif file.
Element
For this we need to define a div element which will hold the loading animation element.
<div class="loader"></div>
This element will overlay the full screen so here we position the element fixed and z-index to 10001 to place this element above all other elements. To cover the full screen, we define height and width to 100%.
.loader { height: 100%; width: 100%; background: #fff; position: fixed; right: 0; top: 0; z-index: 10001; }
Animation
For the animation, we are using pseudo element instead of additional HTML elements as it will give us the flexibility to add loading animation element any where required by just adding single html element. Since we are using the full screen overlay layout, the animation element will be placed in the center of the screen by absolute positioning the animation element to 50% from top and 50% from right of the screen. For positioning to the absolute center of the screen, we will adjust the right and top margin with half value of the actual height and width of the animation element.
.loader:before { content: ''; border: 1px solid; border-color: #ffa50066 #ffa500 #ffa50066 #ffa500; border-radius: 50%; width: 100px; height: 100px; position: fixed; right: 50%; top: 50%; margin-right: -51px; margin-top: -51px; }
Now our animation element is ready, just that its not spinning yet. To make it spin, we define the spin animation behavior as follows.
@keyframes spin { 0% {transform: rotate(0deg);} 100%{transform:rotate(360deg);} }
Now add the spin property to animation element to make it spin.
animation: spin 1s linear infinite;
The final css looks like this
.loader:before { content: ''; border: 1px solid; border-color: #ffa50066 #ffa500 #ffa50066 #ffa500; border-radius: 50%; width: 100px; height: 100px; position: fixed; right: 50%; top: 50%; margin-right: -51px; margin-top: -51px; animation: spin 1s linear infinite; }
So here our loading animation is ready. We can just .loader element at the required place to display the loading animation.