3

I have this button animation defined: JSFIDDLE

The code is also included here:

HTML

<button>Hover to change color</button>

SCSS

$blue: #0084ff;
$blue-darker: darken($blue, 5);

@keyframes mymove {
    0% {width: 0%}
    100%  {width: 80%}
}

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
button {
  margin: auto;
  background-color: $blue;
  border: 1px solid $blue;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  cursor: pointer;
  position: relative;
   &:hover {
    &:after {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 80%;
      height: 2px;
      background-color: white;
      left: 0;
      right: 0;
      margin: auto;
      animation-name: mymove;
      animation-duration: .5s;
     }
  }
}

It's a simple hover animation. The issue is when the mouse leaves the button, the :after element just disappears. I want to animate the :after element out when the mouse leaves? - How would you do that?

Should I modify the keyframe to also contain the opposite direction? 100% to 0% ? or something completely else?

EDIT:

Difference from this question is that I need to access the after element from the button. I have tried with this:

@keyframes mymove-out {
    from {&:after {
      width: 80%
      }}
    to  {&:after {
      width: 0
    }}
}

And using it on the button

animation: mymove-out .5s ease;

But this doesn't work. How do I access the after element from a keyframe?

Jonas Praem
  • 2,296
  • 5
  • 32
  • 53
  • I do not think you can achieve that only with css animation. you can test it by moving your mouse out while the in animation is still running you would get the same issue. instead of :after make the button position relative and in it add a span height 2px and animate width, using javascript. – vssadineni Dec 18 '18 at 14:10
  • let the span be absolutely positioned. – vssadineni Dec 18 '18 at 14:11
  • Possible duplicate of [How to reverse an animation on mouse out after hover](https://stackoverflow.com/questions/16516793/how-to-reverse-an-animation-on-mouse-out-after-hover) – Corné Dec 18 '18 at 14:14
  • @Corne difference from that is that i need to access the after element from the parent / button. The thread has a point in defining the out animation on the button itself. -halfway there – Jonas Praem Dec 18 '18 at 14:19

1 Answers1

2

You can simplify your code with a background coloration and a transition:

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  border: 1px solid #0084ff;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  cursor: pointer;
  background:
   linear-gradient(#fff,#fff) 50% calc(100% - 3px) no-repeat,
   #0084ff;
  background-size:0% 2px;
  transition:.5s all;
   
}

button:hover {
  background-size:80% 2px;
}
<button>Hover to change color</button>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415