csshovertransitionoverlapping

Css hovering and overlapping elements problem


Here's codepen link with button I'd like to use on my website: https://codepen.io/nikolett_codes/pen/BMmOxO

here's HTML code:

<div class="phone cta">Call us</div>
<div class="phone number">(453) 416-4742</div>

And the problem: https://i.sstatic.net/SKn2N.gif

Let's say "OP" is .cta original position, "NP" is .cta new position. What is annoying is that if you hover over cta element and then move your cursor over it (at NP), the animation is not interrupted. Hover, when you hover over OP when .cta div is at NP (so basically hovering over .number div) it interrupts and goes back to OP. How can i deal with it?

One way would be making transition when hovering over .number, but it's not possible because of z-index, so the animation will never start. Another way would be to get .number position and apply eventlistener to this area, I suppose? What is the best way to deal with this problem?


Solution

  • One way to solve this problem is to wrap both the .phone.cta and .phone.number divs inside a container div, and apply the :hover pseudo-class to the container instead of the .phone.cta div.

    <div class="phone-container">
      <div class="phone cta">Call us</div>
      <div class="phone number">(453) 416-4742</div>
    </div>
    

    And add this to the css :

    .phone-container {
          position: relative;
       }
        
       .number {
          z-index: 0;
          position: relative;
       }
       .phone-container:hover .cta {
          transform: translateX(-80%);
          transition: 1.2s;
       }