How to animate gradient background smoothly

后端 未结 3 1362
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:55

    How to animate gradient colors with keyframes:

    // Beggin
    #demo {
      width: 200px;
      height: 200px;
      position: absolute;
      background: linear-gradient(to right, #f06 0%, #60f 100%);
      z-index: 2;
    }
    
    /* Use a 'Before' element to change the background */
    #demo::before {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      background: linear-gradient(to left, #f06 0%, #60f 100%);
      /* Give it an Opacity of 0 and create your animation property: */
      opacity: 0;
      animation: bg 2800ms ease-in-out 0s infinite alternate-reverse;
      z-index: -1;
    }
    
    /* Now call the keyframe-function */
    @keyframes bg {
      0% {
        opacity: 0;
      }
      100% {
        opacity: 1;
      }
    }
    
    /* Unnecessary styling: */
    h3 {
      color: #fff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -130%);
      font-family: Helvetica, Arial, sans-serif;
    }

    CWM

提交回复
热议问题