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

后端 未结 3 980
执念已碎
执念已碎 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条回答
  •  旧时难觅i
    2021-01-23 12:55

    Alteratively, if you're not up to using @keyframes (although I don't see why not), you can use pseudo elements to act as the middle color. All you need to do is control the delay of the transitions using transition-delay:

    .element {
        width: 100px;
        height: 100px;
        background-color: red;
        -webkit-transition: all 0.4s ease;
        transition: all 0.4s ease;
        position: relative;
        -webkit-transition-delay: 0.4s;
        transition-delay: 0.4s;
    }
    
    .element:before {
        position: absolute;
        width: 100%;
        height: 100%;
        content: "";
        background: green;
        -webkit-transition: all 0.4s ease;
        transition: all 0.4s ease;
        opacity: 0;
        -webkit-transition-delay: 0s;
        transition-delay: 0s;
    }
    
    .element:hover:before {
        opacity: 1;
        -webkit-transition-delay: 0.4s;
        transition-delay: 0.4s;
    }
    
    .element:hover {
        background-color: yellow;
        -webkit-transition-delay: 0s;
        transition-delay: 0s;
    }

提交回复
热议问题