user9645391
user9645391

Reputation:

How to make CSS animation to do vice versa after being completed?

The code below is a part of my code :

.myBox:hover::after {
   animation-name: underline;
   animation-duration: 350ms;
   animation-fill-mode: forwards;
}

@keyframes underline {
   from { width: 0; }
   to { width: 100%; }
}

It works nicley, but I want to do it vice versa when animation completed, I mean when it finished then width should be 0 again, In fact for this part I want to do it when my element is not hovered. Which property can help me ?

Upvotes: 1

Views: 225

Answers (3)

oakar
oakar

Reputation: 1265

.myBox:hover::after {
   animation-name: underline infinite;
   animation-duration: 350ms;
   animation-fill-mode: forwards;
}

@keyframes underline {
   from { width: 0; }
   to { width: 100%; }
}

You infinite for this

Upvotes: -1

Temani Afif
Temani Afif

Reputation: 272965

You need to use alternate and run 2 iterations of the animation:

.box {
   height:200px;
   background:red;
   animation: underline 500ms alternate 2 forwards;
}

@keyframes underline {
   from { width: 0; }
   to { width: 100%; }
}
<div class="box">

</div>

Or consider the use of transition if you want the effect on hover:

.box {
  height: 200px;
  background: red;
  width: 0;
  transition: 500ms;
}

body:hover .box {
  width: 100%;
}
<div class="box">

</div>

Upvotes: 1

Rom
Rom

Reputation: 143

You can specify multiple values for animations rather then from and to using percentage:

@keyframes underline {
    0%, 100% { width: 0; }
    50% { width: 100%; }
}

More detailed information can be found here.

Upvotes: 1

Related Questions