1

I have a button and I want to play a basic CSS animation on click.
:focus is the kind of thing I need but it won't reactivate on another click
:active sort of works, but you have to hold it down for the animation to finish
:after strait up doesn't work
And all of these attempts go back to the hover after they're done, which is something I don't want.

button {
  background-color: rgb(32, 32, 32);
  border: none;
  color: rgb(223, 223, 223);
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  transition: color 0.2s ease-out, background-color 0.2s ease-out;
}

button:hover {
  color: rgb(32, 32, 32);
  background-color: rgb(223, 223, 223);
}

@keyframes buttonOnclick {
  0% {
    color: rgb(32, 32, 32);
    background-color: rgb(39, 196, 235);
  }
  100% {
    color: rgb(223, 223, 223);
    background-color: rgb(32, 32, 32);
  }
}

button:focus {
  animation-name: buttonOnclick;
  animation-duration: 1s;
}
<button>This is a button</button>

EDIT: I have found a new fix. Instead of using an animation, :active will contain the clicking and then set transition to be 0 seconds. When you un-click, it will fade back to the hover or idle, whichever happens.

button {
  background-color: rgb(32, 32, 32);
  border: none;
  color: rgb(223, 223, 223);
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  transition: color 0.2s ease-out, background-color 0.2s ease-out;
}

button:hover {
  color: rgb(32, 32, 32);
  background-color: rgb(223, 223, 223);
}

button:active {
  color: rgb(32, 32, 32);
  background-color: rgb(39, 196, 235);
  transition: color 0s ease-out, background-color 0s;
}
<button>This is a button</button>
  • Hello, welcome to stackoverflow. Please take the [tour] and read [ask]. Please paste your code here using the stack snippet, not the jsfiddle or other code hosting service. – ppwater Dec 27 '20 at 05:02
  • 1
    Sounds like you might want to use JavaScript to add a class on click for a specific duration, and apply your styles to that – robinsax Dec 27 '20 at 05:03
  • Yeah, sadly `active` appears to be the best you've got if you just want pure CSS. –  Dec 27 '20 at 05:07

0 Answers0