我想使用这种技术并更改SVG颜色,但到目前为止我还不能这样做。我在CSS中使用这个,但我的图像总是黑色的,无论如何。
我的代码:
.change-my-color { 填充:绿色; } svg < > <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src=" ppngback .png" /> < / svg >
我想使用这种技术并更改SVG颜色,但到目前为止我还不能这样做。我在CSS中使用这个,但我的图像总是黑色的,无论如何。
我的代码:
.change-my-color { 填充:绿色; } svg < > <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src=" ppngback .png" /> < / svg >
当前回答
Manish Menaria的回答有一些问题,如果我们转换白色,它会显示灰色。
所以我添加了一些调整,下面的例子特别展示了如何改变材质图标的颜色:
<mat-icon class="draft-white" svgIcon="draft" aria-hidden="false"></mat-icon>
.draft-white{
filter: brightness(0) invert(1);
}
其他回答
Manish Menaria的回答有一些问题,如果我们转换白色,它会显示灰色。
所以我添加了一些调整,下面的例子特别展示了如何改变材质图标的颜色:
<mat-icon class="draft-white" svgIcon="draft" aria-hidden="false"></mat-icon>
.draft-white{
filter: brightness(0) invert(1);
}
解决方案1 -编辑SVG指向currentColor
<svg>... fill: currentColor stroke: currentColor ...</svg>
然后你可以从你的CSS内容中控制笔画和填充的颜色:
svg {
color: blue; /* Or any color of your choice. */
}
利与弊:
简单,使用常规支持的CSS。
合适的如果:
你可以控制SVG SVG可以内联包含在HTML中。
解决方案2 - CSS掩码属性
<i class="icon"></i>
.icon {
-webkit-mask-size: cover;
mask-size: cover;
-webkit-mask-image: url(https://url.of.svg/....svg);
mask-image: url(https://url.of.svg/....svg);
background-color: blue; /* Or any color of your choice. */
width: 20px;
height: 20px;
}
}
利弊
相对容易使用 浏览器对掩码CSS属性的支持是部分的。
合适的如果:
SVG是外部的,通过URL包含 意味着在现代已知的浏览器上使用。
解决方案3 - CSS过滤器属性-静态颜色
如果预先知道颜色,可以使用https://codepen.io/sosuke/pen/Pjoqqp找到将SVG更改为所需颜色所需的筛选器。例如,将svg转换为#00f:
<img src="https://url.of.svg/....svg" class="icon">
.icon {
filter: invert(8%) sepia(100%) saturate(6481%) hue-rotate(246deg) brightness(102%) contrast(143%);
}
如果你的原始颜色不是黑色,在滤镜列表中加上亮度(0)饱和度(100%)的前缀,将其首先转换为黑色。
利与弊:
可能会有一个小的,不显著的差异之间的结果和期望的颜色。
合适的如果:
想要的颜色是预先知道的。 外部形象
最短的bootstrap兼容方式,没有JavaScript:
.cameraicon {
height: 1.6em; /* Set your own icon size */
mask: url(/camera.svg); /* Path to your image */
-webkit-mask: url(/camera.svg) no-repeat center;
}
像这样使用它:
<td class="text-center">
<div class="bg-secondary cameraicon"/><!-- "bg-secondary" sets actual color of your icon -->
</td>
最简单的方法是使用https://icomoon.io/app/#/select之类的服务从SVG创建字体。上传你的SVG,点击“生成字体”,包括字体文件和CSS内容到你的侧,只是使用和样式它像任何其他文本。我总是这样使用它,因为它使造型更容易。
但正如@CodeMouse92评论的文章中提到的,图标字体会破坏屏幕阅读器(而且可能不利于SEO)。所以还是坚持使用svg吧。
2020的答案
CSS过滤器适用于所有当前的浏览器
改变任何SVGs的颜色
Add the SVG image using an <img> tag. <img src="dotted-arrow.svg" class="filter-green"/> To filter to a specific color, use the following Codepen (click here to open the codepen) to convert a hexadecimal color code to a CSS filter: For example, output for #00EE00 is filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%); Add the CSS filter into this class. .filter-green{ filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%); }