Styles are overwritten when multiple multiple SVG inlined on same page due to embedded style tags
sadokmtir opened this issue · 4 comments
When you have two embedded svgs on the same page, the style tags that are contained in each svg can conflict... often because the same designer used the same layer names or styles in the original document. There are not namespaces per document inlined svg, and no natural separation as when letting the browser load from file, so when embedding multiple files in the page, the style tag of the second svg tag will effect the first.
For example, here are two style tags which are both valid in their own documents, but make a problem when embedded on the same page
<style type="text/css">.st0{fill:#F6B62E;} .st1{display:none;fill:#181818;} .st2{fill:#181818;}</style>
<style type="text/css">.st0{fill:#181818;} .st1{fill:#F6B62E;}</style>
The last one overrides the first one.
hey,
That's how the cascading in CSS works...
I can't think in a way to change these declarations reliably within <style />
tags since there's no clear pattern on how people write them.
If you have a suggestion, feel free to open a PR.
How?
Since there's no pattern on how people write style
tags within SVGs, how can I scope it reliably?
If it helps anyone, one solution is to install the svgo
package and use it with their inlineStyles
plugin to embed the style directly into each svg node instead of declaring classes in a <style>
tag.
For example:
import React from 'react';
import SVG from 'react-inlinesvg';
import { optimize } from 'svgo/lib/svgo';
function optimizeSVG(svg) {
const { data } = optimize(svg, {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
inlineStyles: {
onlyMatchedOnce: false,
},
},
},
},
],
});
return data;
}
export default function App() {
return (
<main>
<SVG
src="https://cdn.svgporn.com/logos/react.svg"
preProcessor={optimizeSVG}
/>
</main>
);
}