Reputation: 437
I want to move an image from right to left, the image should enters from the right side of the screen and exits from left side of the screen, for that I have written this css animation code but it is not working please help.
.CSS file
.imageAnimation {
position: 100% 0px;
-webkit-animation: moveToLeft 10s linear infinite;
animation: moveToLeft 10s linear infinite;
}
@-webkit-keyframes moveToLeft {
from {position: 100% 0px;}
to {position: 0% 0px;}
}
@keyframes moveToLeft {
from {position: 100% 0px;}
to {position: 0% 0px;}
}
.HTML file
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<link rel="stylesheet" type="text/css" href="animation.css"/>
</head>
<body>
<img class="imageAnimation" style="position:absolute; top:0px; left:100%;" src="enemy.png" width="300" height="100"/>
</body>
</html>
Upvotes: 2
Views: 7027
Reputation: 3286
My answer uses calc
and percentages so the box will start outside of the right side of the screen, across the view port area and out of the left side of the screen. You can read about calc browser support here. Heres the code:
.wrap {
background: pink;
height: 200px;
overflow: hidden;
position: relative;
width: 100%;
}
.box {
animation-name: moveToLeft;
animation-duration: 5s;
background-color: red;
height:100px;
left:calc(0% - 100px);
position:absolute;
width:100px;
}
@keyframes moveToLeft {
0% {left:calc(100% + 100px);}
100% {left:calc(0% - 100px);}
}
<div class="wrap">
<div class="box"></div>
</div>
I use a parent container with an overflow: hidden
so the scroll bar will not show when the box is out of the frame. Also the 100px
you see in the calc
will need to be the same width as your element. Here is a js.fiddle with the code. Hope that helps.
Upvotes: 1
Reputation: 122105
Try this
body {
position: relative;
overflow-x: hidden;
}
img {
position: absolute;
animation: moveImage 3s linear infinite;
left: -350px;
}
@keyframes moveImage {
100% {
transform: translateX(calc(100vw + 350px));
}
}
<img src="http://placehold.it/350x150">
350px in translateX(calc(100vw + 350px));
is width
of image so image will go to end of window + width
of image. So you will have to change that for width of your image, same for left: -350px
.
Upvotes: 3
Reputation: 17487
You're actually really close...just using position
incorrectly. Use top
and left
instead.
.imageAnimation {
position: absolute;
left: 100%;
top: 0px;
-webkit-animation: moveToLeft 10s linear infinite;
animation: moveToLeft 10s linear infinite;
}
@-webkit-keyframes moveToLeft {
from {left: 100%;}
to {left: 0%;}
}
@keyframes moveToLeft {
from {left: 100%;}
to {left: 0%;}
}
Upvotes: 2