Oliver Harris
Oliver Harris

Reputation: 35

How to make an animation that moves infinitely right, down, left, and up?

I'm trying to make an animation that moves infinitely to the right, then down, then to the left, and then up (in a loop).

Can you please help me? Thanks :)

Upvotes: 0

Views: 537

Answers (3)

Ilijaz
Ilijaz

Reputation: 58

This is actually very easy using css animations.

This is the code for the animation you're looking for:

This will make sure your object will first move to the right, then down, etc...

@keyframes animation_example {
  0% { transform: translate(0, 0); }
  25% { transform: translate(100px, 0); }
  50% { transform: translate(100px, 100px); }
  75% { transform: translate(0px, 100px); }
}

Than you need to set the animation of your element. The infinite will make sure that the animation will never and and the 5s are the total duration of the animation.

.your-element {
  animation: animation_example infinite 5s;
}

If you want you can check out my little codepen that I created as an example: https://codepen.io/IlijazM/pen/mdPjqbv?editors=0100

Upvotes: 2

Abdul Moeez
Abdul Moeez

Reputation: 1401

I Hope this one will help you out to achieve your goal.

div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes example {
  0%   {background-color:black; left:0px; top:0px;}
  25%  {background-color:black; left:200px; top:0px;}
  50%  {background-color:black; left:200px; top:200px;}
  75%  {background-color:black; left:0px; top:200px;}
  100% {background-color:black; left:0px; top:0px;}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div></div>

</body>
</html>

For Your Information: The @keyframes rule specifies the animation code. The animation is created by gradually changing from one set of CSS styles to another.

Upvotes: 2

Sam
Sam

Reputation: 761

For more information on CSS Animation

div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes example {
  0%   {left:0px; top:0px;}
  25%  {left:100px; top:0px;}
  50%  {left:100px; top:100px;}
  75%  {left:0px; top:100px;}
  100% {left:0px; top:0px;}
}
<div></div>

Upvotes: 2

Related Questions