Is it possible in CSS to transition through a third color when using a hover transition?

后端 未结 3 979
执念已碎
执念已碎 2021-01-23 12:02

I have an element that is red in resting state, and green when the user hovers their cursor over it. I have it set to ease the transition for 0.4s.

Instead

3条回答
  •  孤独总比滥情好
    2021-01-23 12:46

    you could use keyframes for this:

    .element {
      background-color: red;
      height: 300px;
      width: 300px;
    }
    .element:hover {  
      -webkit-animation: changeColor 0.4s forwards;
      animation: changeColor 0.4s forwards;
    }
    
    @-webkit-keyframes changeColor{
      0%{background: red;}
      50%{background:yellow}
      100%{background:green}
      }
    @keyframes changeColor{
      0%{background: red;}
      50%{background:yellow}
      100%{background:green}
      }


    This works by adding the keyframe sequence when the element is hovered, and not during the actual element's creation (so the keyframes only work during the hovered stage).

    The forwards declaration is used so that the animation will 'pause' on the '100%' keyframe, rather than looping back and 'finishing where it started'. I.e. the first keyframe.


    Please note: Other prefixes will need to be included see here for more info.

提交回复
热议问题