How to implement various transitions in and from three different states

I am trying to make a button with different background colors (light green, green, dark green) based on three states (default, freezing, active) and transitions between states as follows:

When user:

  • hovering above the button (default → hover), it should instantly switch from light green to green.
  • presses the button (guidance → active), it should instantly go from green to dark.
  • releases a click (active → hover), it should disappear from dark green to green.
  • 'unhovers', (hover → default), it should fade from green to light.

The only way I was able to do this was with JavaScript, which is not perfect. From what I understand, this may not be possible, because I can only define one hover transition, which happens for both the default → hover parameter and clicked → hover. What I want will require a transition from the default → hover be 0s / none, and a transition from clicked → hover will be 1s / something. Is this possible without using JavaScript?

Here are two snippets of what I have tried so far. The first shows the desired behavior when pressed, and the second - when it hangs.

button {
  height: 100px; width: 400px;
  border: none; outline: none;

  background-color: lightgreen;
  transition: 1s;
}
/* unwanted fade going from default -> hover */
button:hover {
  background-color: green;
  transition: 1s;
}

button:active {
  background-color: darkgreen;
  transition: 0s;
}
<button></button>
Run codeHide result

button {
  height: 100px;
  width: 400px;
  outline: none;
  border: none;
  
  background-color: lightgreen;
  transition: 1s;
}

button:hover {
  background-color: green;
  transition: 0s;
}
/* wanted but missing fade when going from active -> hover */
button:active {
  background-color: darkgreen;
  transition: 0s;
}
<button></button>
Run codeHide result
+4
source share
1 answer

. . Chrome Safari. Firefox .

button {
  height: 100px;
  width: 400px;
  outline: none;
  border: none;
  
  background-color: lightgreen;
  transition: background-color 1s;
}

button:hover {
  background-color: green;
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAHCAIAAABRDCAKAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB98MEhYaBya+xvUAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAABNJREFUCNdjZGhgwA+YGBiGjQoAfXAAjqFknA0AAAAASUVORK5CYII=');
  transition: background-image 1s;
}
button:active {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAOCAIAAABGj2DjAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB98MEhYUHtxWQ7sAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAABhJREFUKM9jZEhhIBUwMTCM6hnVM6j1AABGTwCARo/YOwAAAABJRU5ErkJggg==');
  transition: 0s;
}
<button></button>
Hide result
+2

Source: https://habr.com/ru/post/1620822/


All Articles