3

I have a scenario where I need to immediately change the background colour on hover, and revert back immediately to the original colour on dehovering. This is simple enough with:

#el {
    background-color: black;
}
#el:hover {
    background-color: gray;
}

However, I'm having an issue where I also need to immediately change the background colour on active, but to use a transition when active is released.

#el:active {
    background-color: green;
}

#el:hover:deactivate { /*does not exist*/
    background-color: gray;
    transition: background-color 1s ease;
}

#el:deactivate { /*does not exist either*/
    background-color: black;
    transition: background-color 1s ease;
}

I can't do this by setting #el:hover because then the hover entry also gets animated and I can't do this on #el itself because then dehovering also gets animated.

Is there any way to do this using pure CSS and without JS?

3
  • can you show us your html Commented Oct 16, 2018 at 5:48
  • Here is a jsfiddle of the scenario jsfiddle.net/ewtmc6kg Commented Oct 16, 2018 at 6:12
  • Don’t think that is possible in CSS. You want the entering of one state (the “normal” one) to be treated two different ways, depending on which state it is entered from – but there is no way to make that distinction in CSS.
    – misorude
    Commented Oct 16, 2018 at 6:49

2 Answers 2

3

You can use :not(:active)

#el:active {
    background-color: green;
}

#el:not(:active):hover {
    background-color: gray;
    transition: background-color 1s ease;
}

#el:not(:active) {
    background-color: black;
    transition: background-color 1s ease;
}
<a href="#" id="el">active</a>

3
  • that what you mean? Commented Oct 16, 2018 at 5:53
  • In theory, yes, but in practice, no, because #el:not(:active):hover is the same as #el:hover which results in an entry transition when you hover. Have added a jsfiddle to your comment on my question Commented Oct 16, 2018 at 6:11
  • I think you must use js or Jquery Commented Oct 16, 2018 at 6:36
1

You can simulate this using a pseudo element and you will be able to manage two different things. The hover will change the background and the active state will change the pseudo-element:

#el {
  color: white;
  background-color: black;
  border: 1px solid white;
  height: 200px;
  width: 200px;
  position:relative;
  z-index:0;
}
#el:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:transparent;
  transition:1s;
}

#el:hover {
  background-color: gray;
}

#el:active::before {
  background: green;
  transition: 0s;
}
<div id="el">
  CONTENT HERE
</div>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.