Can I change the fill color of an svg path with CSS?

后端 未结 8 1690
抹茶落季
抹茶落季 2020-11-28 21:09

I have the following code:

  
     

        
8条回答
  •  日久生厌
    2020-11-28 21:23

    I came across an amazing resource on css-tricks: https://css-tricks.com/using-svg/

    There are a handful of solutions explained there.

    I preferred the one that required minimal edits to the source svg, and also didn't require it to be embedded into the html document. This option utilizes the tag.


    Add the svg file into your html using ; I also declared html attributes width and height. Using these width and heights the svg document does not get scaled, I worked around that using a css transform: scale(...) statement for the svg tag in my associated svg css file.

    
    

    Create a css file to attach to your svn document. My source svg path was scaled to 16px, I upscaled it to 64 with a factor of four. It only had one path so I did not need to select it more specifically, however the path had a fill attribute so I had to use !IMPORTANT to force the css to take precedent.

    #svg2 {
        width: 64px; height: 64px;
        transform: scale(4);
    }
    path {
        fill: #333 !IMPORTANT;
    }
    

    Edit your target svg file, before the opening tag, to include a stylesheet; Note that the href is relative to the svg file url.

    
    

    提交回复
    热议问题