简体   繁体   中英

SVG: Why can I not override the fill color?

I with to have a default fill and override where needed:

 <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <defs> <circle fill="blue" id="myCircle" cx="0" cy="0" r="5" /> </defs> <use class="one" x="5" y="5" href="#myCircle" /> <use class="two" x="5" y="5" href="#myCircle" fill="red" /> </svg>

However, both circles are blue.

I also tried using CSS to set.two to fill: red, however both circles remain blue.

Why is this and can it be changed?

The issue

fill="red" is ignored here, because stroke was already set on #myCircle. Most attributes (except for x, y, width and height) do not override those set in the ancestor.

The solution

Basicly removing the fill property on #myCircle will fix the issue.

Here are a couple of example on how you can change the fill and stroke of svg elements using css

 .circles { display: flex; gap: 1rem; }.super-circle { width: 100px; height: 100px; }.super-circle circle { stroke: maroon; stroke-width: 2px; }.super-circle--blue circle { fill: blue; }.super-circle--red circle { fill: red; }.super-circle--green circle { fill: green; stroke: purple; }
 <div class="circles"> <svg class="super-circle super-circle--blue" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <circle cx="5" cy="5" r="4" /> </svg> <svg class="super-circle super-circle--red" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <circle cx="5" cy="5" r="4" /> </svg> <svg class="super-circle super-circle--green" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <circle cx="5" cy="5" r="4" /> </svg> </div>

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