Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ending a running transition at new hover in pure css

Tags:

css

transition

I am trying to end (overwrite) a running transition in pure css. The css-code that tries to overwrite doesn't work; it isn't just ignored and I can't explain the behaviour.

Below is an example-code with 3 links each followed by 1 div. 3 more div are added afterwards just for testing.

div {
  background-color: white;
  width: 50px;
  transition: all;
  transition-delay: 1s;
}
a:hover ~ div {
  width: 50px;
  color: red;
}
a:hover + div {
  width: 100px;
  transition-delay: 0s;
}
<a>link 1</a>
<div>text 1</div>
<a>link 2</a>
<div>tekst 2</div>
<a>link 3</a>
<div>tekst 3</div>
<div>tekst 4</div>
<div>tekst 5</div>
<div>tekst 6</div>
  • At hover on a link, only the first-following div is changed in width because of the + selector.

  • The transition-delay keeps this hover on for 1s extra.

The issue is now that when a new hover happens, I wish all hover-effects on all following boxes to terminate. Think of it as a menu; when hovering a new menupoint, I wish all other submenus to close and only the current one to open.

  • The hope was with the ~ selector to make all following div back to normal width, and then the a:hover + div can expand the width of just the right one. But this doesn't work.

The color: red text-coloring is added for testing. Because after some testing I found out that the issue isn't the ~ selector nor the css-order, but rather the transition. Removing all transition lines and the result is exactly as expected, just without the delays. You can see the results here:

  • Here is a fiddle with the above non-working code, and
  • here is a fiddle with the transition code-lines removed, where it all works (but missing the delay).

Without transition code-lines all following div get red text - also the three extra ones in the bottom. But with the transitions code-lines, they are not colored red - in fact only the hovered one is coloered red, which means that the code-lines are not entirely ignored, but doesn't work as a ~ selector anymore.

Conclusion is that the transitions interfere. I apparently can't stop a running transition and the interfering chunk of code is behaving unexpectedly and not ignored.

What is exactly the behaviour of the transitions code lines that causes this?


For those curious I can tell that in reality on the project I'm working on the original width before hover is 0. Therefore this solution will work:

a:hover ~ div {
  display:none;
}

Instead of trying to reset the width, I remove the width and all is good. I am rather asking the question above to understand, what the issue is.

like image 536
Steeven Avatar asked Nov 09 '22 05:11

Steeven


1 Answers

You were almost there, just add transition: none to your a:hover ~ div

https://jsfiddle.net/e3p97ewj/

like image 71
phobia82 Avatar answered Nov 15 '22 11:11

phobia82