Search code examples
htmlcsssvgtransition

SVG circle and line transition not working


I'm trying to implement a simple toggle based on an SVG icon. However, I'm not able to get transition work on either circle or line, although is does for the parent. I think it might be redundant to add circle and line to transition, but I still did, just to be sure.

svg, circle, line {
  transition: all 0.2s ease-in-out;
}

svg:hover {
  transform: rotate(45deg);
}

svg:hover circle {
  fill: #d5f0e5;
  stroke: #00884e;
}

svg:hover line {
  stroke: #00884e;
}
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="9.5" stroke="#515663"/>
<line x1="10.0555" y1="5" x2="10.0555" y2="15" stroke="#2A303E"/>
<line x1="5" y1="9.94434" x2="15" y2="9.94434" stroke="#2A303E"/>
</svg>


Solution

  • The stroke color transitions do work, but .2s is really fast, maybe that's why you thought it wasn't working?
    However, you can't transition from <color>none to non-none <color>, you need to set it to transparent if you want the interpolation to work:

    svg, circle, line {
      transition: all 2s ease-in-out; /* set to 2s to clearly show if it works */
    }
    
    svg:hover {
      transform: rotate(45deg);
    }
    
    svg:hover circle {
      fill: #d5f0e5;
      stroke: #00884e;
    }
    
    svg:hover line {
      stroke: #00884e;
    }
    <!-- changed the 'fill' attribute from "none" to "transparent" to allow transitionning -->
    <svg width="20" height="20" viewBox="0 0 20 20" fill="transparent" xmlns="http://www.w3.org/2000/svg">
      <circle cx="10" cy="10" r="9.5" stroke="#515663"/>
      <line x1="10.0555" y1="5" x2="10.0555" y2="15" stroke="#2A303E"/>
      <line x1="5" y1="9.94434" x2="15" y2="9.94434" stroke="#2A303E"/>
    </svg>

    Or as commented below, you could also play with the fill-opacity property for the same effect and probably better browser support.