Search code examples
csscss-animations

Animating hover - delay underline until hover animation finishes


I'm encountering an issue with implementing a hover effect on underlined links using SCSS. I'm aiming to create a transition where, on hover, the text color changes to red, and the underline disappears momentarily before being redrawn in red from left to right. When hover finishes first the red underline should dissapear and only then the original, black underline should appear again (without animation). The first step works, however, I'm having trouble ensuring that the transition from the hovered element finishes before the non-hovered element is displayed. I've tried experimenting with transition-delay but to no avail. You can see the issue in the following code - notice how black underline appears BEFORE the red line completely shrinks when hover ends (on mouse leave). Can you help?

a {
  position: relative;
  text-decoration: underline;
  color: black;
  transition: color 0.3s;
}

a::before {
  content: '';
  position: absolute;
  width: 0;
  height: 1px;
  bottom: 0;
  left: 0;
  background-color: red;
  transition: width 0.3s;
}

a:hover {
  text-decoration: none;
  color: red;
}

a:hover::before {
  width: 100%;
}
<a href="google.com">My link to Google</a>


Solution

  • Set transition-delay to a text-decoration-color in normal state:

    a {
      position: relative;
      text-decoration-line: underline;
      color: black;
      transition: color 0.3s, text-decoration-color 0s 0.3s;
    }
    
    a::before {
      content: '';
      position: absolute;
      width: 0;
      height: 1px;
      bottom: 0;
      left: 0;
      background-color: red;
      transition: width 0.3s;
    }
    
    a:hover {
      text-decoration-color: transparent;
      color: red;
      transition: width 0.3s;
      transition: color 0.3s;
    }
    
    a:hover::before {
      width: 100%;
    }
    <a href="google.com">My link to Google</a>