What I want precisely is to make a button that fades into another color when the mouse hovers it, but instantly changes color on a click. In other words, the color would change slowly when the mouse enters or leaves it, but abruptly when the user presses the mouse button or releases it.
The problem is that I can't dissociate the two. Here is what I tried:
<html>
<head>
<style>
button {
width: 40vw;
height: 20vw;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid gray;
border-radius: 0;
cursor: pointer;
transition-duration: 0.7s;
}
button:hover {
background-color: lightgray;
}
button:active {
background-color: darkgray;
transition-duration: 0s;
}
</style>
</head>
<body>
<button>
Click here
</button>
</body>
</html>
Sadly, the transition-duration
property inside the button:active
rule only affects the transition in one way, not in the other. The transition lasts 0 sec on pressing click, but it lasts 0.7 sec on release.
The reason is that it is in fact a transition to button:hover
. But I can't add transition-duration: 0s
in the button:hover
rule because I still want the transition to be smooth when the mouse enters the button. And I cannot differentiate the case where the previous selector was button
from that where it was button:active
.
I could use JavaScript events but the problem seems basic enough to have a css-only solution.
Edit: I almost bypassed it with the following code, which would work perfectly if you didn't enter the button again after the first click. As it is still focused, the transition is immediate this time.
button:hover {
background-color: lightgray;
}
button:focus {
background-color: lightgray;
transition-duration: 0s;
}
button:active {
background-color: darkgray;
transition-duration: 0s;
}
button:not(:hover) {
background-color: #efefef;
transition-duration: 0.7s;
}
CodePudding user response:
Don't use the same property and you can do it. Use background-image
and a gradient to have the color on the active state and it won't trigger the transition
button {
width: 40vw;
height: 20vw;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid gray;
border-radius: 0;
cursor: pointer;
transition-duration: 0.7s;
}
button:hover {
background-color: lightgray;
}
button:active {
background-image: linear-gradient(darkgray 0 0);
}
<button>Click here</button>