SASS mixin to convert a hex to a CSS filter
Asked Answered
A

1

8

Is there a way to create a SASS mixin that will create a CSS filter from a HEX value? I have SVG images with different colors depending on the site and hate to hard code all the filters.

#000000

to

filter: brightness(0) saturate(100%) invert(0%) sepia(100%) saturate(7500%) hue-rotate(18deg) brightness(115%) contrast(115%);

Below is an example in Javascript to take a hex and output the following

https://codepen.io/sosuke/pen/Pjoqqp

Abreast answered 23/5, 2020 at 14:24 Comment(2)
Hey, Did you find any solution?Reta
I have no, just manually created the filterAbreast
P
5

Here is an example scss mixin: https://jsfiddle.net/Tegos/3fchp0qm/

@mixin recolor($color: #000, $opacity: 1) {
  $r: red($color) / 255;
  $g: green($color) / 255;
  $b: blue($color) / 255;
  $a: $opacity;

  // grayscale fallback if SVG from data url is not supported
  $lightness: lightness($color);
  filter: saturate(0%) brightness(0%) invert($lightness) opacity($opacity);

  // color filter
  $svg-filter-id: "recolor";
  filter: url('data:image/svg+xml;utf8,\
    <svg xmlns="http://www.w3.org/2000/svg">\
      <filter id="#{$svg-filter-id}" color-interpolation-filters="sRGB">\
        <feColorMatrix type="matrix" values="\
          0 0 0 0 #{$r}\
          0 0 0 0 #{$g}\
          0 0 0 0 #{$b}\
          0 0 0 #{$a} 0\
        "/>\
      </filter>\
    </svg>\
    ##{$svg-filter-id}');
}

Source: https://mcmap.net/q/46663/-how-to-transform-black-into-any-given-color-using-only-css-filters

Philps answered 25/2, 2021 at 9:20 Comment(1)
This is the correct answer for windows. Apparently, it doesn't work on MacOs.Wilding

© 2022 - 2024 — McMap. All rights reserved.