简体   繁体   中英

How inherit stroke color in SVG? (Not fill, but stroke color)

I have an .SVG where I call with <img src="/image/arrow.svg" alt="Arrow"> . Everything is good, but I would like to dynamically set a different stroke color (Not fill color...) for my SVG like <img ... style="color:red"> . I read that I could use fill="currentColor" on my path,but how could I do for my stroke color?

My SVG file:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100">
    <path d="M20 10 H90 V80" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
    <path d="M10 90 L100 0" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path>
</svg>

My html:

<img src="/image/arrow.svg" alt="Arrow" style="color:red">

As Robert Lognson correctly stated, and previously discussed on StackOverflow , svg used as an image element has a new image context, thus it does not use the document's styles, whereas an inline svg element does use them.

So the following example works:

 svg.red { color: red; }
 <svg class="red" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100"> <path d="M20 10 H90 V80" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path> <path d="M10 90 L100 0" fill="transparent" stroke="currentColor" stroke-width="20" stroke-linecap="round"></path> </svg>

If you take out the inline style from the SVG, you can manipulate the colour, borders, etc. using CSS like so:

 svg { stroke: #47ccd1; fill: transparent; stroke-width: 20px; stroke-linecap: round; transform: scale(0.3); } 
 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="100" width="100"> <path d="M20 10 H90 V80"></path> <path d="M10 90 L100 0"></path> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM