简体   繁体   中英

How to change the color of an .svg image using css?

I am working with Sass and images that are in .svg format, I am using them as if they were .jpg (or any other) images.

This is the icon (a capture): the icon .jpg

I want to know how can I make it so that its color can change using css?

I am using the .svg image like this:

 .text::before { content: " "; display: block; background: url("./../Iconos/Icono\\ some-icon.svg"); background-repeat: no-repeat; background-position: center; cursor: pointer; width: 35px; height: 35px; float: right; } 
 <div class="text"> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Doloribus assumenda error reiciendis soluta rerum corporis, illo aspernatur laboriosam accusamus nisi fugiat amet possimus cumque eum id enim dolor repudiandae expedita.</p> </div> 

if you use like this you won´t be able to change the color, you can use better in your html like this,

<img src="image.svg" /> 

and convert the svg img in code in order to have access to svg path and modify in CSS

 svg path {
    fill: #783cbc;
}

You can convert with this function in javascript

  $('img.svg').each(function(){
         var $img = jQuery(this);
         var imgID = $img.attr('id');
         var imgClass = $img.attr('class');
         var imgURL = $img.attr('src');

         $.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Add replaced image's ID to the new SVG
            if(typeof imgID !== 'undefined') {
               $svg = $svg.attr('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if(typeof imgClass !== 'undefined') {
               $svg = $svg.attr('class', imgClass+' replaced-svg');
            }

            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
            if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
               $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
            }

            // Replace image with new SVG
            $img.replaceWith($svg);

         }, 'xml');

      });

But maybe what you want to do is make a font with the icons in order to change the color easily, in that case there are several options to do that, you can do it with https://icomoon.io/ or if you are using grunt you can use https://github.com/sapegin/grunt-webfont

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM