Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS mixin to convert a hex to a CSS filter

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

like image 290
Mike Flynn Avatar asked May 23 '20 14:05

Mike Flynn


People also ask

What is the purpose of using mixin in sass?

Sass Mixins The @mixin directive lets you create CSS code that is to be reused throughout the website. The @include directive is created to let you use (include) the mixin.


Video Answer


1 Answers

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://stackoverflow.com/a/62880368/4293444

like image 164
Tegos Avatar answered Oct 14 '22 07:10

Tegos