Create line loading animation using css

Viewed 417

Hey i have tried animation on a 2px solid line that fill white color from center to its end but failed because it just filled right to left and not gained from direction inverse. Can any body tells me how to create the animation that work like this: This is just the structure. The 2px height and 100px width just from the point + and fill the color from center to the ends in equal length from left and right and complete this type of animation. Hope I had explained my question with detail.

[----------+----------]
[---------+++---------]
[--------+++++--------]
[-------+++++++-------]
[------+++++++++------]
[-----+++++++++++-----]
[----+++++++++++++----]
[---+++++++++++++++---]
[--+++++++++++++++++--]
[-+++++++++++++++++++-]
[+++++++++++++++++++++]
3 Answers

something like below:

.line {
  width:100px;
  height:2px;
  background:linear-gradient(red 0 0) center/0% 100% no-repeat;
  animation:l 2s linear infinite alternate;
}

@keyframes l {
  to {background-size:100% 100%}
}
<div class="line"></div>

Solution with stroke-dasharray

A line 100px long is drawn from the center with two rays.

  • Before starting animation stroke-dasharray: 0.50 0.50; both rays have a dash equal to zero, and the maximum gap length is 50px. Therefore, the line is initially invisible.
  • At the end of the animation, the gap of both rays become equal to zero, and the dash takes on a maximum value of 100px, so the line becomes fully visible

#pol{
  fill:none;
  stroke:red;
  stroke-width:2;
  stroke-dasharray:0,50 0,50;
  animation:mid 2s linear infinite alternate;
 }
 @keyframes mid {
 to {stroke-dasharray:0,0,100,0;}
 }
<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="200" height="200" viewBox="0 0 200 200" >  
<polyline id="pol" stroke-dasharray="0,100" points="50,50 150,50"  >
 </polyline> 
 <text x="100" y="46" font-size="24px" text-anchor="middle" fill="black"> animate</text>
</svg>     

The trick here for making from center to left is decreasing margin-left in animation

.wrapper {
  position: relative;
  width: 200px;
  height: 2px;
  background-color: #000000;
}

#inner-right,
#inner-left {
  width: 0;
  height: 100%;
  background: white;
}

#inner-left {
  margin-left: 50%;
  animation: centerToLeft 2000ms ease forwards infinite;
}

#inner-right {
  position: absolute;
  top: 0;
  left: 50%;
  animation: centerToRight 2000ms ease forwards infinite;
}

@keyframes centerToRight {
  to {
    width: 50%;
  }
}

@keyframes centerToLeft {
  to {
    margin-left: 0;
    width: 50%;
  }
}
<div class="wrapper">
  <div id="inner-left"></div>
  <div id="inner-right"></div>
</div>

Related