csscss-transitionsbackground-imagegradientbackground-color

Transition a CSS background-color to a gradient


I have some tiles that have an ordinary background-color and show a CSS gradient on hover, and I want to add a transition between these. I've seen this solution, but as far as I can tell the only way to make it work for background colours is to treat it as a gradient by adding two duplicate initial colours and transitioning those:

@property --myColor1 {
  syntax: '<color>';
  initial-value: #e6e6e6;
  inherits: false;
}

@property --myColor2 {
  syntax: '<color>';
  initial-value: #e6e6e6;
  inherits: false;
}

This seems redundant and it feels like there should be a cleaner way to do this. Is there?


Solution

  • You can fade the opacity of the upper layer which is a one-color gradient:

    @property --o {
      syntax: '<number>';
      initial-value: 1;
      inherits: false;
    }
    
    .box {
      --c: purple; /* the color */
      
      background:
       conic-gradient(rgb(from var(--c) r g b/var(--o)) 0 0),
       linear-gradient(red,blue); /* the gradient */
      transition: --o .5s;
      height: 200px;
    }
    .box:hover {
      --o: 0;
    }
    <div class="box"></div>

    Another syntax:

    @property --o {
      syntax: '<number>';
      initial-value: 1;
      inherits: false;
    }
    
    .box {
      --c: purple; /* the color */
      
      border-image: conic-gradient(rgb(from var(--c) r g b/var(--o)) 0 0) fill 0;
      background: linear-gradient(red,blue);
      transition: --o .5s;
      height: 200px;
    }
    .box:hover {
      --o: 0;
    }
    <div class="box"></div>