score:1

If you want to use things like gradient backgrounds with SVG, you can, but you need to do it the SVG way. SVG has gradients and you can apply them in css, but you need to define them in SVG. Once you do that, you can use css to apply them, or swap them out with :hover etc. Here's a super-simple example that might help and should be easy to use with D3.

    rect.rec {
      fill: url("#grad");
    }
    rect.rec:hover {
      fill: url("#grad_rev")
    }
<div>

  <svg width="200", height="200">
    <defs>
    <linearGradient id="grad">
      <stop offset="5%" stop-color="#d33" />
      <stop offset="95%" stop-color="#100" />
    </linearGradient>
    <linearGradient id="grad_rev">
        <stop offset="5%" stop-color="#100" />
        <stop offset="95%" stop-color="#d33" />
      </linearGradient>
    </defs>
    <rect class="rec" width="100", height="100">
    
    </rect>
  </svg>

</div>

Here' a more complete snippet using a D3 transition to set the stop color on the SVG gradient. It's a little more difficult than simple CSS but very flexible and gives you things you can't easily get with css like traditions between gradients.

    var margin = {top: 20, right: 30, bottom: 30, left: 40},        
        width = 200 - margin.left - margin.right,
        height = 200 - margin.top - margin.bottom,
        padding = 0.3;

    var chart = d3.select(".chart")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    
    chart.append("rect")
        .attr("class", "rec")
        .attr("height", "150px")
        .attr("width", "150px")
        .on("mouseover", handleMouseOver)
        .on("mouseout", handleMouseOut)

    function handleMouseOver(d, i){
        d3.select('#red-stop')
        .transition()
        .duration(600)
        .attr('stop-color', 'blue' )
    }
    function handleMouseOut(d, i){
        d3.select('#red-stop')
        .transition()
        .duration(600)
        .attr('stop-color', 'red' )
    }
        rect.rec {
            fill: url("#grad");
        }
<script src="https://d3js.org/d3.v4.min.js"></script>

<svg class="chart">
    <linearGradient id="grad">
        <stop id="red-stop" offset="5%" stop-color="red" />
        <stop offset="95%" stop-color="#100" />
    </linearGradient>
    <linearGradient id="grad_rev">
        <stop offset="5%" stop-color="#100" />
        <stop offset="95%" stop-color="#d33" />
    </linearGradient>
          
  </svg>


Related Query