Keyframes Animation has no transition when moving in other direction (Pure CSS)
I have this Keyframe Animation where i move a dot in a square:
* {
margin: 0;
padding: 0;
}
#dot {
height: 10px;
width: 10px;
background: #000;
border-radius: 100%;
position: absolute;
animation: moveDotOne 2s infinite;
transition: all 0.3s;
top: 0;
left: 0;
}
@keyframes moveDotOne {
0% {
top: 0;
}
25% {
top: 20px;
}
50% {
left: 20px;
}
75% {
top: 0;
}
100% {
left: 0;
}
}
<div id="dot"></div>
The only problem is that the 25% keyframe is already running when the 0% isn't even finished. How can i fix that?
Think about what the animation is making it transition the value from.
When it hits 50%
it sets left: 20px
. So it then transitions from something to 20px
. What is that something?
You haven't specified anything. So it is the default value.
You can't transition from auto
so it jumps.
Set starting values for left
and top
in your CSS. Don't assign them only with the animation.
As pointed out you need to think about both x&y positions for the transitions - added variables here to make the effect easier to observe. At each keyframe a x and y position (top,left) are specified.
* {
margin: 0;
padding: 0;
}
:root{
--d:80px;
--w:90px;
}
#box{
padding:1rem;border:1px solid red;
width:var(--w);
height:var(--w);
}
#dot {
height: 10px;
width: 10px;
background: #000;
border-radius: 100%;
position: absolute;
animation: moveDotOne 5s infinite;
transition: all 0.3s;
margin:1rem;
}
@keyframes moveDotOne {
0% {
top:0;
left:0;
}
25% {
top:var(--d);
left:0;
}
50% {
top:var(--d);
left:var(--d);
}
75% {
top:0;
left:var(--d);
}
100%{
top:0;
left:0;
}
}
<div id='box'>
<div id="dot"></div>
</div>