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 there a way to apply styles to a particular SVG only?
Here is an example where differenty styles are used within SVG but the second applies to the first aparently.
<svg>
<style>
line {
stroke: red;
}
</style>
<line x1="0" y1="0" x2="100" y2="100">
</svg>
<svg>
<style>
line {
stroke: blue;
}
</style>
<line x1="0" y1="0" x2="100" y2="100">
</svg>
https://codepen.io/anon/pen/LmmyEe
Edit
Maybe this is a better example:
<svg>
<style>
.colored {
stroke: red;
}
</style>
<line class="colored" x1="0" y1="0" x2="100" y2="100">
</svg>
<svg>
<style>
.colored {
stroke: blue;
}
</style>
<line class="colored" x1="0" y1="0" x2="100" y2="100">
</svg>
I would like to be able to let the user edit the style of each of these SVGs so that the user needs to know only what a class does for all the SVGs. If I would use different classes, like "colored1" and "colored2" or so, that would make it trickier for the user which I want to avoid.
You could target them using
nth-child
or a similar selector: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)
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:And the above is the same as using external CSS:
Another idea is to use CSS variable that you define on your SVG (or on a wrapper) as inline style: