将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>
下面是另一种解决方案,使用渐变和单色图标作为背景和背景混合模式来着色图标。
它要求背景色是白色的,否则整个背景都会上色。我只在Chrome上进行了测试。
.colored-background {
background-image: linear-gradient(45deg, green, green), url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23000000%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E');
background-color: #fff;
background-blend-mode: lighten, normal;
background-repeat: no-repeat;
background-position: center, center right .8em;
background-size: auto, 0.6em;
color: red;
display: inline-flex;
align-items: center;
padding: 0.5em;
padding-right: 2em;
height: 1.6em;
width: auto;
border: 1px solid gray;
}
.bg {
background-color: #ddd;
padding: 1em;
}
<div class="bg">
<div class="colored-background">green icon from black svg</div>
</div>
对于单色背景,您可以使用带有掩码的SVG,其中应该显示背景颜色
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" preserveAspectRatio="xMidYMid meet" focusable="false" style="pointer-events: none; display: block; width: 100%; height: 100%;" >
<defs>
<mask id="Mask">
<rect width="100%" height="100%" fill="#fff" />
<polyline stroke-width="2.5" stroke="black" stroke-linecap="square" fill="none" transform="translate(10.373882, 8.762969) rotate(-315.000000) translate(-10.373882, -8.762969) " points="7.99893906 13.9878427 12.7488243 13.9878427 12.7488243 3.53809523"></polyline>
</mask>
</defs>
<rect x="0" y="0" width="20" height="20" fill="white" mask="url(#Mask)" />
</svg>
然后使用这个CSS
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
background-image: url(your/path/to.svg);
background-color: var(--color);