Search code examples
htmlcsssvgcss-variables

Use a CSS-variable in SVG via <img>


I have an SVG which I currently display via an <img src="foobar.svg">. The parent HTML has some CSS associated which defines variables which I need in the SVG. The SVG has a <style> to hotlink this.

The CSS-variables defined in the parent seem to not be available to the SVG. Is there some way to make it work? I can't just copy the CSS; I could, as last resort, inline the SVG into the HTML.

The current setup is something to the tune of

<html>
<head>
<link rel="stylesheet" href="the_css_that_defines_the_variables.css">
</head>
<body>
<img src="foobar.svg">
...

<svg>
<style type="text/css">svg { fill: var(--myvariable) }</style>
...
</svg>

Solution

  • Variables cannot be transferred from one document to another. Within a single HTML document, variables can be declared in the inline style attribute of individual elements, but that's about as far as you can go.

    If the variable must be a CSS variable, you'll need to inline that SVG for it to be able to use it.