Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply transition for single pseudoclass

I want a transition on my button which should only be applied on hover but not on other pseudoclasses.

button {
    width: 100px;
    height: 50px;
    color: white;
    background-color: green;
    transition: background-color 1s;
}

button:hover {
    background-color: blue;
}

button:active {
    background-color: red;
}
<button>Nice Button!</button>

So in this case I want it the transition from green to blue on hover but not from blue to red when active. How can I achieve it?

like image 735
DonJuwe Avatar asked Jan 10 '23 06:01

DonJuwe


2 Answers

Set transition: none; on :active pseudo class + if you don't want a transition on mouseup, you can add

button:focus {
  background-color: blue;
  transition: none;
}

button {
  width: 100px;
  height: 50px;
  color: white;
  background-color: green;
  transition: background-color 1s;
}
button:hover {
  background-color: blue;
}

button:focus:hover {
  background-color: blue;
  transition: none;
}
button:active:hover {
  background-color: red;
  transition: none;
}
<button>Nice Button!</button>
like image 190
web-tiki Avatar answered Jan 22 '23 02:01

web-tiki


I have to admit that your question is challenging !

My proposed solution:

button {
    width: 100px;
    height: 50px;
    color: white;
    background-color: green;
    transition: background-color 2s;
}

button:hover {
    background-color: blue;
}

button:active {
/*    background-color: red; */
    -webkit-animation: activate 0s 0s forwards;
    animation: activate 0s 0s forwards;
}

@-webkit-keyframes activate {
    0% {background-color: green;}
   100% {background-color: red;}
}

@keyframes activate {
    0% {background-color: green;}
   100% {background-color: red;}
}

fiddle

The problem is that the base state is shared beteen the back transition from the hover and the activer pseudo classes, so I don'tthink this can be solved using only transitions.

The trick is not to change the color in the active state, it is still green inside, but it looks red :-)

like image 21
vals Avatar answered Jan 22 '23 03:01

vals