I am very clear that they animation
are transition
for animations, but...
Suppose I want to move an element from left to right, both can be done.
Example with animation
:
document.getElementById('button').onclick = e => {
document.getElementById('img').classList.add('move');
}
#img {
position: relative;
height: 50px;
}
@keyframes move {
0% { left: 0; }
100% { left: 200px; }
}
.move {
animation: move 2s forwards;
}
<img id="img" src="https://a.imge.to/2019/08/11/fjHnk.th.jpg"/><br/>
<button id="button">Mover</button>
Example with transition
:
document.getElementById('button').onclick = e => {
document.getElementById('img').classList.add('move');
}
#img {
position: relative;
height: 50px;
left: 0;
transition: left 2s;
}
#img.move {
left: 200px;
}
<img id="img" src="https://a.imge.to/2019/08/11/fjHnk.th.jpg"/><br/>
<button id="button">Mover</button>
- At some point should I use one or the other?
- What advantage does one have over the other?
CSS animations
An animation contains the following properties :
animation-name
animation-duration
animation-timing-function
animation-delay
animation-iteration-count
animation-direction
animation-fill-mode
animation-play-state
Then we observe the following:
For example, in the following fragment we animate the figure that is inside the circle with an infinite rotation:
So an animation allows us to establish complex and iterable behavior of different elements on the screen.
That is why to establish the behavior of all of them
fotogramas
we have a rule calledkeyframes
in which inside we can indicate the behavior that each step of the animation will have:For example:
Even if they are triggered by user interaction, for example if the previous animation occurs when the user clicks
:hover
on the element of theDOM
.CSS transitions
Transitions in CSS have the following properties:
transition-duration
transition-timing-function
transition-delay
transition-property
Where these only allow us to have 2 states, one initial and one final without intermediate animation effects.
For the example above, what we would get would be something similar to this:
Where we change the background color through the property
transition
indicating the affected property, the duration of the transition and the regularity with which it will be displayed.Then we can identify that: