Using CSS to transition the fill property of an SVG path on hover

前端 未结 2 673
时光取名叫无心
时光取名叫无心 2020-12-07 15:37

I\'m including an SVG image file on my page within an object tag, like this:


            


        
      
      
      
2条回答
  •  [愿得一人]
    2020-12-07 16:19

    In order to transition/fade, CSS needs a starting value and an ending value.
    Because you set the color for the path using the SVG attribute fill="#FAFAFA", CSS doesn't process it and the transition doesn't fade.

    Instead if you use CSS to set the color, the transition will behave as expected

    So all I had to do to make the transition work is give the #europe a starting fill to transition from.

     path { transition: fill .4s ease; }
     /* set fill for before and for during hover */
     #europe       path { fill: red; }
     #europe:hover path { fill: white; }
    

    Here's a working JSFiddle.


    Or, doing it inline can be more convenient (style=""):

    
    

    Just in order for CSS to do your fading, it needs to handle the start and end values in CSS/inline style (as opposed to using the SVG fill= attribute).

提交回复
热议问题