How to restrict CSS style to apply to a particular

2019-09-21 18:26发布

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.

标签: html css svg
2条回答
唯我独甜
2楼-- · 2019-09-21 18:59

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

svg:nth-child(1) line {
  stroke: black;
}
<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>

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)

查看更多
我命由我不由天
3楼-- · 2019-09-21 19:08

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>
<line x1="0" y1="0" x2="100" y2="100"/>
</svg>

<svg>
  <style>
    svg:nth-of-type(2) line {
      stroke: blue;
    }
  </style>
  <line x1="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>

<line x1="0" y1="0" x2="100" y2="100"/>
</svg>

<svg>

  <line x1="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);
}

}
<svg style="--s:red">
  <line x1="0" y1="0" x2="100" y2="100"/>
</svg>
<span style="--s:green">
<svg >
  <line x1="0" y1="0" x2="100" y2="100"/>
</svg>
</span>

查看更多
登录 后发表回答