A
A
Artyom Innokentiev2015-05-30 00:41:03
css
Artyom Innokentiev, 2015-05-30 00:41:03

Through what to do animation when hovering over (hover): transition or @keyframes?

I'm doing an animation on hover. Tried in two ways:
1) through transition:

.master_figure p
{
  opacity: 0;
  text-align: center;
  background-color: black;
  transition: 0.5s ease-out;
  transform: translateY(0px);
  color: white;
}

.master_figure:hover p
{
  opacity: 0.8;
  transition: 0.5s ease-out;
  transform: translateY(-25px);
}

2) via @keyframes:
.master_figure p
{
  text-align: center;
  background-color: black;
  color: white;
}

.master_figure:hover p
{
  animation: pIn 0.5s ease forwards;
}

@keyframes pIn
{
  0% {opacity: 0; transform:translateY(0px);}
  100% {opacity: 0.8; transform: translateY(-25px);}
}

I liked the second option better, because the animation is separated from such settings as centering, color and background color - I think it's more logical.
Which option is more correct? Why? Also, in the second case, there is a problem - when I remove the cursor, everything returns without animation, if anyone knows the answer - tell me, please)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay Talanov, 2015-05-30
@artinnok

Keyframes are needed for cyclic, "one-sided" or complex (many steps with many changes of different properties) animation. For example, the shine effect for a button, when a semi-transparent element is swept at an angle, creating a glowing effect. If done as a transition - after removing the mouse from the element, the shining block will go back. And with a keyframe, it will pass 1 time from left to right with each hover. https://cssanimation.rocks/pseudo-elements/ - here is the actual example.
Transitions are respectively used when, for example, it is necessary to change the properties of an element when hovering or adding a class. At the same time, when adding / removing different classes, you can set up your convenient timings / delays everywhere on how the properties will change. In general, convenient declarativeness in all fronts.
Oh yes, keyframes are also needed when it is necessary to turn on the animation at the start of the page without resorting to js.
https://cssanimation.rocks/transition-vs-animation/ - you can still check this.

M
Mark, 2015-05-30
@printf

Transition is better, precisely because of "when I remove the cursor, everything is without animation." In general, keyframes are made for more complex things, for example, when you need to drive something along waypoints (i.e. along a complex route), and do other non-linear things. If there are only 0% and 100% in keyframes, this is an overkill.
You can separate in the code purely visually, if it is important.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question