I have an SVG Image which is to be loaded on my webpage as the background. Hence the css for it is:
body{
background: url('path/to/the/svg/image.svg')
.
.
}
I have a css variable named accent-primary-color
, which defines the accent color of the page (and is set by the user) and I want the color to be reflected in the SVG as the main color. The svg file has a style tag as follows:
<style>
.outline-paths{
fill: var(--accent-primary-color);
}
</style>
I would have achieved the color in SVG, if it were a code in the HTML file, but in case of background-image
, that won't work because its and external SVG, being used as background and it doesn't have access to the CSS Variables.
I also found methods to achieve the thing using Data URI
methods like:
background: url('data:image/svg+xml;utf8,<svg ...> ... </svg>');
but I can't use that because the SVG Code is very long (602 Lines without minifying), and it also has several single and double quotes in the file.
Is there any other method through which the SVG File can access the CSS Variables while being used as a background image.
You can use a modern Web Component
--rectcolor
<style>
into the SVGbackgroundImage
<style>
:root{
--rectcolor:rebeccapurple;
}
</style>
<svg-import-background src="//svg-cdn.github.io/red.svg"></svg-import-background>
<svg-import-background src="//svg-cdn.github.io/blue.svg"></svg-import-background>
<script>
customElements.define("svg-import-background", class extends HTMLElement {
async connectedCallback() {
let svg = await (await fetch(this.getAttribute("src"))).text();
svg = svg.replace(/\>[\t\s\n ]+\</g, "><"); // replace all BETWEEN tags
svg = svg.replace(/#/g, "%23");
svg = svg.replace(/"/g, "'");
let color = getComputedStyle(this).getPropertyValue("--rectcolor");
let style = `<style>rect{fill:${color}}</style>`;
svg = svg.replace("</svg>",style + `</svg>`);
this.style.display="inline-block";
this.style.width="100px";
this.style.height="100px";
this.style.backgroundImage = `url("data:image/svg+xml;charset=UTF-8,${svg}")`;
}
})
</script>