SVGs override each others CSS-style
Asked Answered
M

3

6

I am working with Vue.js and try to place some SVG Icons I made in Illustrator for my Webapp. I loaded the icons with Webpacks "require". It is not possible to access the svg's with their source (src attribute of img tag) so we insert them with vue like that:

<div class="section-icon" v-html="getIconForEvent(event)"></div>

This displays the right icons at the right place, but I ran into some problems with this approach.

The SVGs are all styled with a style-tag within the svgs. So the last SVG overwrites the style of all previous SVGs because they somehow all have the same class. In the Chrome Devtools this looks like this.

What can I do to not let the style of SVGs overwrite each others classes? I didnt put the style tags there myself, those are just the style that the SVG had itself. Thanks!

Milksop answered 7/8, 2018 at 11:13 Comment(0)
S
11

There is nothing you can do other than modifying the class names in each SVG so that they don't clash.

It looks like you are using Illustrator to produce those SVGs. To work around the problem, make sure you tell Illustrator, when you save the SVG, to not use <style> elements for element styling.

When you save, use File > Save As > SVG, then click on "More Options" and change the "CSS Properties" setting. If it is set to "Style Elements", change it to one of the other options. If you do that, it won't use classes and your SVGs won't clash with one another.

To fix your current SVGs, you should be able to load them in, then resave them using the method above.

Styracaceous answered 7/8, 2018 at 12:8 Comment(0)
C
0

If this works for your implementation, you can render the SVGs as a CSS background-image instead of inline elements. This will prevent their styles from interfering with each other.

<template>
  <div class="section-icon" :style="iconStyle"></div>
</template>

<script setup>
const svgContent = ... // Your way of obtaining the SVG icon content

const iconStyle = computed(() => {
  return svgContent.value
    ? {
        backgroundImage: `url('data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent.value)}')`,
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
      }
    : {};
});
</script>
Chanticleer answered 10/10 at 12:20 Comment(0)
S
-2

Try targeting them via CSS using children:

.cls-3:first-child {
   fill:yellow;
}
.cls-3:nth-child(2) {
   fill:red;
}

...

.cls-3:last-child {
   fill:blue;
}

Fill with what colors you need to see if it works. If that does not overwrite it, you may need to use !important, although it is not a best practice, rather a worst case scenario.

Sullage answered 7/8, 2018 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.