Search code examples
javascripthtmlcsssvg

Changing the fill color of SVG image loaded by data-URL inside a stylesheet


I want to have different colored images that are loaded inside of a stylesheet via url('data...') property. All images are embedded inside of the css-file. The only difference is the fill color that should be used. Here is my current code:

.icon.save {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="%23666666" d="M397.944 258.597l0 22.9362c0,7.22714 -5.91315,13.1403 -13.1403,13.1403l-292.742 0c-7.22714,0 -13.1403,-5.91315 -13.1403,-13.1403l0 -22.9362 319.022 0zm-354.98 -209.156l395.673 0c3.31637,0 6.02912,2.65813 6.02912,5.90747l0 403.401c0,3.24863 -2.71346,5.90747 -6.02912,5.90747l-86.1661 0 0 -20.4653 9.24335 0 0 6.27915 68.7657 0 0 -386.843 -32.536 0 0 184.33 -319.022 0 0 -184.33 -27.8006 0 0 370.473 16.4964 16.3701 42.2982 0 6.30256 -6.27915 5.25633 0 0 14.7884 -5.69823 5.67695 -54.0028 0 -24.8386 -24.6481 0 -384.66c0,-3.24934 2.71275,-5.90747 6.02877,-5.90747zm299.498 419.709l-210.978 0 0 -127.463c0,-7.78962 6.37313,-14.1628 14.1624,-14.1628l182.654 0c7.78927,0 14.1624,6.37313 14.1624,14.1628l0 127.463zm-177.925 -133.337l54.4986 0 0 113.007 -54.4986 0 0 -113.007z"/></svg>');
}

.icon.save:hover, .icon.save.bright {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="white" d="M397.944 258.597l0 22.9362c0,7.22714 -5.91315,13.1403 -13.1403,13.1403l-292.742 0c-7.22714,0 -13.1403,-5.91315 -13.1403,-13.1403l0 -22.9362 319.022 0zm-354.98 -209.156l395.673 0c3.31637,0 6.02912,2.65813 6.02912,5.90747l0 403.401c0,3.24863 -2.71346,5.90747 -6.02912,5.90747l-86.1661 0 0 -20.4653 9.24335 0 0 6.27915 68.7657 0 0 -386.843 -32.536 0 0 184.33 -319.022 0 0 -184.33 -27.8006 0 0 370.473 16.4964 16.3701 42.2982 0 6.30256 -6.27915 5.25633 0 0 14.7884 -5.69823 5.67695 -54.0028 0 -24.8386 -24.6481 0 -384.66c0,-3.24934 2.71275,-5.90747 6.02877,-5.90747zm299.498 419.709l-210.978 0 0 -127.463c0,-7.78962 6.37313,-14.1628 14.1624,-14.1628l182.654 0c7.78927,0 14.1624,6.37313 14.1624,14.1628l0 127.463zm-177.925 -133.337l54.4986 0 0 113.007 -54.4986 0 0 -113.007z"/></svg>');
}

As you can see, the only difference is the fill="" attribute of the path. Is there any other way with any inline css code i might add?


Solution

  • The only way I've found is to generate my svgs with a small (self written) tool, that converts the colors to fit my needs. But there is no solution that can change the colors on runtime. So each colors doubles size for each image. However the tool adds the ability to generate something like an imagemap as css. Often this is used for png icons, that are arranged on a large picture to avoid multiple http requests.