Modify SVG fill color when being served as Background-Image

后端 未结 16 1197
再見小時候
再見小時候 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:10

    You can create your own SCSS function for this. Adding the following to your config.rb file.

    require 'sass'
    require 'cgi'
    
    module Sass::Script::Functions
    
      def inline_svg_image(path, fill)
        real_path = File.join(Compass.configuration.images_path, path.value)
        svg = data(real_path)
        svg.gsub! '{color}', fill.value
        encoded_svg = CGI::escape(svg).gsub('+', '%20')
        data_url = "url('data:image/svg+xml;charset=utf-8," + encoded_svg + "')"
        Sass::Script::String.new(data_url)
      end
    
    private
    
      def data(real_path)
        if File.readable?(real_path)
          File.open(real_path, "rb") {|io| io.read}
        else
          raise Compass::Error, "File not found or cannot be read: #{real_path}"
        end
      end
    
    end
    

    Then you can use it in your CSS:

    .icon {
      background-image: inline-svg-image('icons/icon.svg', '#555');
    }
    

    You will need to edit your SVG files and replace any fill attributes in the markup with fill="{color}"

    The icon path is always relative to your images_dir parameter in the same config.rb file.

    Similar to some of the other solutions, but this is pretty clean and keeps your SCSS files tidy!

提交回复
热议问题