Skip to content Skip to sidebar Skip to footer

How To Restrict Css Style To Apply To A Particular Svg Only?

I have several SVGs that I would like to style using CSS. However, the styles seem to be applied across SVGs. Unfortunately, I cannot use classes on SVG elements or a iframe. Is

Solution 1:

You could target them using nth-child or a similar selector:

svg:nth-child(1) line {
  stroke: black;
}
<svg><style>
    line {
      stroke: red;
    }
  </style><linex1="0"y1="0"x2="100"y2="100"/></svg><svg><style>
    line {
      stroke: blue;
    }
  </style><linex1="0"y1="0"x2="100"y2="100"/></svg>

If you can't do this, then just wrap it in an element and add a class to that, which you can then use to target the svg

Or you could use inline styles in your svgs (but I'm guessing if you can't add classes, you can't edit the svg)

Solution 2:

If you know how your SVG are placed within your HTML and there is no way to add ID or classes, you can rely on nth-of-type/nth-child to restrict your rules to only one element:

<svg><style>
    svg:nth-of-type(1) line {
      stroke: red;
    }
  </style><linex1="0"y1="0"x2="100"y2="100"/></svg><svg><style>
    svg:nth-of-type(2) line {
      stroke: blue;
    }
  </style><linex1="0"y1="0"x2="100"y2="100"/></svg>

And the above is the same as using external CSS:

svg:nth-of-type(1) line {
  stroke: red;
}

svg:nth-of-type(2) line {
  stroke: blue;
}
<svg><linex1="0"y1="0"x2="100"y2="100"/></svg><svg><linex1="0"y1="0"x2="100"y2="100"/></svg>

Another idea is to use CSS variable that you define on your SVG (or on a wrapper) as inline style:

line {
  stroke: var(--s,#000);
}

}
<svgstyle="--s:red"><linex1="0"y1="0"x2="100"y2="100"/></svg><spanstyle="--s:green"><svg ><linex1="0"y1="0"x2="100"y2="100"/></svg></span>

Post a Comment for "How To Restrict Css Style To Apply To A Particular Svg Only?"