CSS text background hover effect behaving strangely on mouseout

Deadly 提交于 2019-12-10 14:57:41

问题


I've implemented a hover effect on a h1 element (see code and pen below), but the effect is behaving strangely on mouse out and sort of flickering before going back to it's original state.

Any ideas how to make it transition back to it's original color as smoothly as it fades in on hover?

Thanks in advance.

https://codepen.io/lobodemon/pen/YOXKNJ

h1 {
  transition: 0.5s;
}

h1:hover {
  background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
  background-size: 400% 400%;
  color:transparent;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-animation: Gradient 15s ease infinite;
  -moz-animation: Gradient 15s ease infinite;
  animation: Gradient 15s ease infinite;
}

@-webkit-keyframes Gradient {
    0%, 100% {
        background-position: 0 50%
    }
    50% {
        background-position: 100% 50%
    }
}

@-moz-keyframes Gradient {
    0%, 100% {
        background-position: 0 50%
    }
    50% {
        background-position: 100% 50%
    }
}

@keyframes Gradient {
    0%, 100% {
        background-position: 0 50%
    }
    50% {
        background-position: 100% 50%
    }
}
<h1>The Title</h1>

回答1:


The issue is that you are trying to combine an animation with transtion which will not work like you expect. By adding a transtion you will not make the animation go smooth. In other words, you cannot add transtion to animation.

Since you made the duration of the animation to be 15s on hover, I don't think the infinite is needed in this case because no one will keep hovering more than 15s, so you can change this into a transition and it will be smooth.

I have added the black color to the gradient to have our initial state then with a transition we can do half the initial animation and at the end you will have a 7s duration which is somehow enough for a hover effect:

h1 {
  transition: 7s;
  background: 
    linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB,#000);
  background-size: 400% 400%;
  color:transparent;
  -webkit-background-clip: text;
  background-clip: text;
  background-position: 0 0;
}

h1:hover {
  background-position: 100% 50%;
  
}
<h1>The Title</h1>



回答2:


When you are working with transition, you need to set initial state of element properties that you are going to change.

h1 {
  background: black;
  -webkit-background-clip: text;
  background-clip: text;
}

I also found intresting example with same effect as yours. https://codepen.io/anthony-liddle/pen/uFoxA



来源:https://stackoverflow.com/questions/51968018/css-text-background-hover-effect-behaving-strangely-on-mouseout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!