I want to filter a SVG graphic embedded in CSS to a specific color.
To be specific, I want to use the CSS filter: hue-rotate(),... and not manipulate the SVG (only the fill, or stroke prop).
The HSL values for the color are as follows:
color: hsl(268deg, 50%, 50%);
The SVG graphic has stroke="red", so in HSL:
hsl(0, 100%, 50%)
With the filter:
filter: hue-rotate(268deg) saturate(50%) brightness(100%);
the icon becomes this:
hsl(261, 62%, 38%)
With some effort, I found suitable filter values:
filter: hue-rotate(275deg) saturate(0.325) brightness(1.63);
But these only fit to the used target color.
Is there a way, in CSS, to create a universal filter that always makes the correct target color out of a defined stroke color?
Example
and as a codepen: https://codepen.io/koljal/pen/MWBGGLg
:root {
--link-color: hsl(268deg, 50%, 50%);
}
body {
font-family: sans-serif;
max-width: 50rem;
margin-inline: auto;
background-color: #333;
color: var(--link-color);
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.icon {
background-image: url("data:image/svg+xml;utf8, <svg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' viewBox='0 0 24 24'><path fill='none' stroke='red' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m20 4l-2 14.5l-6 2l-6-2L4 4zM8.5 8h7L11 12h4l-.5 3.5l-2.5.75l-2.5-.75l-.1-.5'/></svg>");
background-size: cover;
background-repeat: no-repeat;
width: 5rem;
height: 5rem;
}
.simple {
filter: hue-rotate(268deg) saturate(50%) brightness(100%);
}
.custom {
filter: hue-rotate(275deg) saturate(0.325) brightness(1.63);
}
<h1>This is the Target color</h1>
<code>
hsl(268deg,50%,50%)
</code>
<h2>SVG icon as CSS-inlne background-image</h2>
<code>
<pre>
fill="red"
aka: hsl(0, 100%, 50%)
</pre>
</code>
<div class="icon"></div>
<h2>simple filter on SVG</h2>
<code>
<pre>
filter: hue-rotate(268deg) saturate(50%) brightness(100%);
</pre>
</code>
<div class="icon simple"></div>
Result:
<code>
<pre>
hsl(261, 62%, 38%)
</pre>
</code>
<h2>custom filter</h2>
<code>
<pre>
filter: hue-rotate(275deg) saturate(0.325) brightness(1.63);
</pre>
</code>
<div class="icon custom"></div>
Result:
<code>
<pre>
hsl(268, 50%, 50%)
</pre>
</code>