Modify SVG fill color when being served as Background-Image

后端 未结 16 1032
再見小時候
再見小時候 2020-11-22 06:31

Placing the SVG output directly inline with the page code I am able to simply modify fill colors with CSS like so:

po         


        
16条回答
  •  情歌与酒
    2020-11-22 07:12

    It's possible with Sass! The only thing you have to do is to url-encode your svg code. And this is possible with a helper function in Sass. I've made a codepen for this. Look at this:

    http://codepen.io/philippkuehn/pen/zGEjxB

    // choose a color
    
    $icon-color: #F84830;
    
    
    // functions to urlencode the svg string
    
    @function str-replace($string, $search, $replace: '') {
      $index: str-index($string, $search);
      @if $index {
        @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
      }
      @return $string;
    }
    
    @function url-encode($string) {
      $map: (
        "%": "%25",
        "<": "%3C",
        ">": "%3E",
        " ": "%20",
        "!": "%21",
        "*": "%2A",
        "'": "%27",
        '"': "%22",
        "(": "%28",
        ")": "%29",
        ";": "%3B",
        ":": "%3A",
        "@": "%40",
        "&": "%26",
        "=": "%3D",
        "+": "%2B",
        "$": "%24",
        ",": "%2C",
        "/": "%2F",
        "?": "%3F",
        "#": "%23",
        "[": "%5B",
        "]": "%5D"
      );
      $new: $string;
      @each $search, $replace in $map {
        $new: str-replace($new, $search, $replace);
      }
      @return $new;
    }
    
    @function inline-svg($string) {
      @return url('data:image/svg+xml;utf8,#{url-encode($string)}');
    }
    
    
    // icon styles
    // note the fill="' + $icon-color + '"
    
    .icon {
      display: inline-block;
      width: 50px;
      height: 50px;
      background: inline-svg('
    
    ');
    }
    

提交回复
热议问题