Today I learned about CSS var inside SVGs
- Written on: Tu Jan 2021
- Last update: Tu Jan 2021
CSS var inside SVG fill
Today I learned that you can use CSS variables inside your SVG fill attributes! Well, at least if your SVG is embedded in your DOM and not called externally. That means, you cannot use CSS variables if you embed your SVG using the <img>
tag and <object>
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
:root {
--color: #ff0000;
}
</style>
</head>
<body>
<svg
width="444"
height="407"
viewBox="0 0 444 407"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M416 3H304V115H416V3ZM304 0H301V3V115V118H304H416H419V115V3V0H416H304ZM212 140H100V252H212V140ZM100 137H97V140V252V255H100H212H215V252V140V137H212H100ZM389 167H277V279H389V167ZM277 164H274V167V279V282H277H389H392V279V167V164H389H277ZM99 292H211V404H99V292ZM96 289H99H211H214V292V404V407H211H99H96V404V292V289ZM-47 182H65V294H-47V182ZM-50 179H-47H65H68V182V294V297H65H-47H-50V294V182V179Z"
fill="var(--color)"
/>
</svg>
</body>
</html>