将SVG输出直接内联到页面代码中,我可以简单地用CSS修改填充颜色,如下所示:

polygon.mystar {
    fill: blue;
}​

circle.mycircle {
    fill: green;
}

这工作得很好,但是我正在寻找一种方法来修改SVG的“填充”属性,当它作为背景-图像时。

html {      
    background-image: url(../img/bg.svg);
}

我现在怎么改变颜色?这可能吗?

作为参考,以下是我的外部SVG文件的内容:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve">
<polygon class="mystar" fill="#3CB54A" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 
    118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/>
<circle class="mycircle" fill="#ED1F24" cx="202.028" cy="58.342" r="12.26"/>
</svg>

当前回答

由于这是谷歌上的问题,尽管年龄很大,我想我不妨在看了这里的选项后,给出一个我在遥远的2022年使用的解决方案。

这实际上只是之前的遮罩解决方案,但在一个伪元素上。

.icon {
    height: 1.5rem;
    width: 1.5rem;
}
.icon::before {
    content: "";
    display: block;
    width: 100%;
    height: 100%;
    mask-repeat: no-repeat;
    mask-position: center;
    mask-size: contain;
    mask-image: url("path/to/svg/icon.svg");
    -webkit-mask-repeat: no-repeat;
    -webkit-mask-position: center;
    -webkit-mask-size: contain;
    -webkit-mask-image: url("path/to/svg/icon.svg");
}

这在今天的所有主流浏览器中都有效,尽管显然您不能使用它来拥有具有多种颜色的SVG。如果站点不允许你内联插入它们,或者你不喜欢字体图标等等,这就是商业成本。

其他回答

 .icon { 
  width: 48px;
  height: 48px;
  display: inline-block;
  background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%; 
  background-size: cover;
}

.icon-orange { 
  -webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4); 
  filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4); 
}

.icon-yellow {
  -webkit-filter: hue-rotate(70deg) saturate(100);
  filter: hue-rotate(70deg) saturate(100);
}

代码本文章和演示

唯一的方法,我发现这是跨浏览器(又名防弹),是渲染SVG与PHP和传递查询字符串来设置颜色。

SVG,这里叫做arrow。php

<?php
$fill = filter_input(INPUT_GET, 'fill');
$fill = strtolower($fill);
$fill = preg_replace("/[^a-z0-9]/", '', $fill);
if(empty($fill)) $fill = "000000";
header('Content-type: image/svg+xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
?>
<svg xmlns="http://www.w3.org/2000/svg" width="7.4" height="12" viewBox="0 0 7.4 12">
    <g>
        <path d="M8.6,7.4,10,6l6,6-6,6L8.6,16.6,13.2,12Z" transform="translate(-8.6 -6)" fill="#<?php echo htmlspecialchars($fill); ?>" fill-rule="evenodd"/>
    </g>
</svg>

然后像这样调用图像

.cssclass{ background-image: url(arrow.php?fill=112233); }

仅适用于PHP。记住,每次你改变颜色值,你的浏览器将加载一个新的图像。

这是我最喜欢的方法,但是您的浏览器支持必须非常先进。使用mask属性可以创建应用于元素的掩码。任何地方的掩模是不透明的,或固体,底层的图像显示通过。在它是透明的地方,底层图像被掩盖或隐藏。CSS mask-image的语法类似于background-image。看看这个相互依赖的掩码

在某些(非常特定的)情况下,这可以通过使用过滤器来实现。例如,您可以通过使用过滤器将色调旋转45度将蓝色SVG图像更改为紫色:hue-rotate(45deg);。浏览器支持很少,但它仍然是一项有趣的技术。

Demo

以文本形式下载svg。

使用javascript修改svg文本来更改绘制/描边/填充颜色[s]。

然后将修改后的svg字符串内联嵌入到您的css中。