Search code examples
csssvglinear-gradients

Is there a way to make the visual effect of linear gradient colors in SVG and CSS the same?


I found that the visual effect of the linear gradient color is different between SVG and CSS, especially in the adjacent part between two colors. I want to know if this is due to differences in linear interpolation. And is there a solution to make the effect of the SVG the same as the CSS?

#rectangle {
  width: 100px;
  height: 300px;
  background: linear-gradient( 180deg, rgba(235, 116, 116, 0.1) 0%, rgba(42, 255, 44, 1) 100%);
}

.stop1 {
  stop-color: rgba(235, 116, 116);
  stop-opacity: 0.1;
}

.stop2 {
  stop-color: rgba(42, 255, 44, 1);
}


/* added by editor for comparrison reasons */

.container {
  display: flex;
  gap: 0.25em;
}
<div class="container">
  <div class="col">
    <p>CSS</p>
    <div id='rectangle'></div>
  </div>

  <div class="col">
    <p>SVG</p>
    <svg width="800" height="800" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="Gradient1" x1="0" x2="0" y1="0" y2="1" spreadMethod="repeat">
          <stop class="stop1" offset="0%" />
          <stop class="stop2" offset="100%" />
        </linearGradient>
      </defs>
      <rect x="0" y="0" rx="0" ry="0" width="100" height="300" fill="url(#Gradient1)" />
    </svg>
  </div>
</div>


Solution

  • Yes, that seems to be correct. Firefox supports color-interpolation on gradients and I believe Chrome will do so soon too.

    #rectangle {
      width: 100px;
      height: 300px;
      background: linear-gradient( 180deg, rgba(235, 116, 116, 0.1) 0%, rgba(42, 255, 44, 1) 100%);
    }
    
    .stop1 {
      stop-color: rgba(235, 116, 116);
      stop-opacity: 0.1;
    }
    
    .stop2 {
      stop-color: rgba(42, 255, 44, 1);
    }
    
    
    /* added by editor for comparrison reasons */
    
    .container {
      display: flex;
      gap: 0.25em;
    }
    <div class="container">
      <div class="col">
        <p>CSS</p>
        <div id='rectangle'></div>
      </div>
    
      <div class="col">
        <p>SVG</p>
        <svg width="800" height="800" version="1.1" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="Gradient1" color-interpolation="linearRGB" x1="0" x2="0" y1="0" y2="1" spreadMethod="repeat">
              <stop class="stop1" offset="0%" />
              <stop class="stop2" offset="100%" />
            </linearGradient>
          </defs>
          <rect x="0" y="0" rx="0" ry="0" width="100" height="300" fill="url(#Gradient1)" />
        </svg>
      </div>
    </div>