Use CSS3 transitions with gradient backgrounds

后端 未结 16 1594
慢半拍i
慢半拍i 2020-11-21 22:18

I\'m trying to transition on hover with css over a thumbnail so that on hover, the background gradient fades in. The transition isn\'t working, but if I simply change it to

16条回答
  •  醉酒成梦
    2020-11-21 23:18

    With Chrome 85 (and also Edge) adding support for @property rule, now we can do this in CSS:

    @property --colorPrimary {
      syntax: '';
      initial-value: magenta;
      inherits: false;
    }
    
    @property --colorSecondary {
      syntax: '';
      initial-value: green;
      inherits: false;
    }
    

    The rest is normal CSS.
    Set initial gradient colors to the variables and also set the transition of those variables:

    div {
      /* Optional: change the initial value of variables
        --colorPrimary: #f64;
        --colorSecondary: brown;
      */
    
      background: radial-gradient(circle, var(--colorPrimary) 0%, var(--colorSecondary) 85%) no-repeat;
      transition: --colorPrimary 3s, --colorSecondary 3s;
    }
    

    Then, on the desired rule, set the new values for variables:

    div:hover {  
    --colorPrimary: yellow;
    --colorSecondary: #f00;
    }
    

    @property --colorPrimary {
      syntax: '';
      initial-value: #0f0;
      inherits: false;
    }
    
    @property --colorSecondary {
      syntax: '';
      initial-value: rgb(0, 255, 255);
      inherits: false;
    }
    
    div {
      width: 200px;
      height: 100px;
      background: radial-gradient(circle, var(--colorPrimary) 0%, var(--colorSecondary) 85%) no-repeat;
      transition: --colorPrimary 3s, --colorSecondary 3s;
    }
    
    div:hover {
      --colorPrimary: red;
      --colorSecondary: #00f;
    }
    Hover over me

    See the full example here and refer here for @property support status.
    The @property rule is part of the CSS Houdini technology. For more info refer here and here.

提交回复
热议问题