0

Is it possible to use a css custom property within an HTML tag for an inline svg element?

Say I have an inline svg element:

<svg style="width:var(--image-width);" />

Now, this statement isn't valid, but is there a way to use --image-width in the HTML file instead of the css file?

Mr No
  • 113
  • 1
  • 10
  • Yes it appears to work for colors. But if I define --image-width:70; in the css file, the custom property does not work. A color does work though, like: --my-color: rgb(10,80,60,0.5) – Mr No Sep 28 '20 at 03:39
  • 1
    You need to specify a unit, try 70px instead of 70. – mclaus Sep 28 '20 at 03:45
  • It appears to work for just about any custom property other than width. – Mr No Sep 28 '20 at 03:47
  • 1
    If you set the display property of the svg to inline it won't work, you could set it to inline-block to make it work. – mclaus Sep 28 '20 at 03:50

1 Answers1

2

It should work if you import a css file that defines the property --image-width.

/* style.css */
:root {
    --image-width: 42px;
}
<!-- Your html file -->
<link rel="stylesheet" href="style.css">
<svg style="width: var(--image-width);">
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
mclaus
  • 142
  • 1
  • 11