Home > database >  SVG: Why can I not override the fill color?
SVG: Why can I not override the fill color?

Time:09-29

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  x="5" y="5" href="#myCircle" />
  <use  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?

CodePudding user response:

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.

CodePudding user response:

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 >
  <svg  viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <circle cx="5" cy="5" r="4" />
</svg>

  <svg  viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <circle cx="5" cy="5" r="4" />
</svg>

  <svg  viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <circle cx="5" cy="5" r="4" />
</svg>
</div>

  • Related