How to animate gradient background smoothly

后端 未结 3 1393
Happy的楠姐
Happy的楠姐 2021-01-29 15:29

I want to achieve an effect than when the user hovers over a div, it\'s background color turns into a gradient that smoothly switches from one corner to the other, repeatedly, u

3条回答
  •  轮回少年
    2021-01-29 15:58

    To animate the background, you need to modify the background position.

    To make the transition smooth, you need to play with opacity - and since you don't want all the element to fade, you need to use a pseudo element for this

    #test{
        width: 200px;
        height: 200px;
        position: relative;
        background-color: rgba(215,54,92,0.7);
        transition: background-color 1s;
    }
    #test:hover{
      background-color: transparent;
    }
    
    #test:after {
      content: "";
      position: absolute;
      left: 0px;
      top: 0px;
      right: 0px;
      bottom: 0px;
      z-index: -1;
        background-image: linear-gradient(45deg, 
                        rgba(215,54,92,0.5), 
                        rgba(215,54,92,0.9),
                        rgba(215,54,92,0.5), 
                        rgba(215,54,92,0.9),
                        rgba(215,54,92,0.5)
                        );
        background-size: 800px 800px;
        background-position: 0px 0px;
        animation: move 2s infinite linear;
        opacity: 0;
        transition: opacity 1s;
    }
    
    #test:hover:after {
        opacity: 1;
    }
    @keyframes move {
      from {background-position: 0px 600px;}
        to {background-position: -800px 600px;}
    }

提交回复
热议问题