html

<img src="logo.svg" alt="Logo" class="logo-img">

css

.logo-img path {
  fill: #000;
}

上面的svg加载并本机填充:#fff,但当我使用上面的css尝试将其更改为黑色时,它没有改变,这是我第一次使用svg,我不知道为什么它不工作。


当前回答

您可以将SVG设置为掩码。通过这种方式设置背景色将充当填充色。

HTML

<div class="logo"></div>

CSS

.logo {
  background-color: red;
  -webkit-mask: url(logo.svg) no-repeat center;
  mask: url(logo.svg) no-repeat center;
}

JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/ MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask

请检查您的浏览器是否支持此功能: https://caniuse.com/#search=mask

其他回答

您可以将SVG设置为掩码。通过这种方式设置背景色将充当填充色。

HTML

<div class="logo"></div>

CSS

.logo {
  background-color: red;
  -webkit-mask: url(logo.svg) no-repeat center;
  mask: url(logo.svg) no-repeat center;
}

JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/ MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask

请检查您的浏览器是否支持此功能: https://caniuse.com/#search=mask

编辑您的SVG文件,将fill="currentColor"添加到SVG标记中,并确保从文件中删除任何其他填充属性。

例如:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 139.435269383854" id="img" fill="currentColor">...
</svg>

注意,currentColor是一个关键字(不是使用的固定颜色)。

在此之后,您可以使用CSS更改颜色,通过设置元素的颜色属性或从它的父元素。

例子:

.div-with-svg-inside {
    color: red;
}

我忘了说,你必须这样插入SVG:

<svg>
   <use xlink:href='/assets/file.svg#img' href="/assets/file.svg#img"></use>
</svg>

如果image来自某个变量,那么

<svg>
  <use [attr.xlink:href]="somevariable + '#img'" [attr.href]="somevariable + '#img'"></use>
</svg>
Note that `#img` is the id of the `svg` tag inside svg file. Also note `xlink:href` has been deprecated instead you should use `href` or use can use both to support older browser versions.

Another way of doing it: [https://css-tricks.com/cascading-svg-fill-color/][1]


  [1]: https://css-tricks.com/cascading-svg-fill-color/

在代码编辑器中打开SVG图标,并在path标记后添加一个类:

<path class'colorToChange' ...

你可以向svg添加class,并像这样改变颜色:

codepen

来自@Praveen的答案是可靠的。

我不能让它在我的工作中响应,所以我为它做了一个jquery悬停函数。

CSS

.svg path {
   transition:0.3s all !important;
}

JS / JQuery

// code from above wrapped into a function
replaceSVG();

// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#CCC');
}, function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#3A3A3A');
});

如果你只是在真实颜色和黑白之间切换图像,你可以设置一个选择器为:

{过滤器:没有;}

另一个是:

{filter:grayscale(100%);}