我想使用这种技术并更改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内容中的背景图像:

背景:url(“数据:photo /svg+xml;charset=utf8,%3Csvg xml ='http://www.w3.org/2000/svg' fill='rgba(1.39,215.1)' viewBox=' ..3e % %3C/svg%3E’);

当然,替换…使用您的内联图像代码。

其他回答

最短的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>

对于Angular用户来说,"inline-svg-2" npm库非常有用:

https://www.npmjs.com/package/ng-inline-svg-2 将<img src="">替换为<div inlineSVG="path_to_assets"></div> 在屏幕的SCSS文件中设置CSS“color:” 在SVG图片中使用fill="currentColor"或stroke="currentColor"。

您现在可以动态配置CSS颜色,包括使用CSS变量,SVG将会适应。

注意:“currentColor”技巧只适用于内联svg,这就是为什么我们需要一个特殊的模块。

如果你想使用CSS来改变颜色,你也可以使用这样的在线工具:使用CSS过滤器改变SVG颜色

带有背景色的框元素上的SVG掩码将导致:

body{ overflow:hidden; } .icon { --size: 70px; display: inline-block; width: var(--size); height: var(--size); transition: .12s; -webkit-mask-size: cover; mask-size: cover; } .icon-bike { background: black; animation: 4s frames infinite linear; -webkit-mask-image: url(https://image.flaticon.com/icons/svg/89/89139.svg); mask-image: url(https://image.flaticon.com/icons/svg/89/89139.svg); } @keyframes frames { 0% { transform:translatex(100vw) } 25% { background: red; } 75% { background: lime; } 100% { transform:translatex(-100%) } } <i class="icon icon-bike" style="--size:150px"></i>


注意- Internet Explorer浏览器不支持SVG掩码

我发现它有点笨拙,但它绝对是一种动态改变<img>标记中包含的SVG颜色的工作方式。

在SVG文件中,您可以通过以下方式添加CSS内容:

<svg ...>
    <defs>
        <style>
            ...
        <style>
    <defs>

在这里可以使用@media规则,SVG可以使用该规则查看自身以外的上下文环境。有一个宽高比媒体特性应用于SVG框(例如,<img>标记)。您可以通过稍微拉伸SVG框来为SVG创建不同的上下文。

通过这种方式,您还可以使favicon与网站上出现的SVG相同,但使用不同的颜色。(在这种情况下,其他SVG框不应该是方形的。)

/* img stretched horizontally (if SVG is square-shaped) */
@media (min-aspect-ratio: 1000/999) {
    path {
        fill: blue;
    }
}

/* img stretched vertically (if SVG is square-shaped) */
@media (max-aspect-ratio: 999/1000) {
    path {
        fill: green;
    }
}

/* img with exact sizes */
@media (aspect-ratio: 86/74) {
    path {
        fill: red;
    }
}

/* favicon with light browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: light) {
    path {
        fill: black;
    }
}

/* favicon with dark browser theme */
@media (aspect-ratio: 1/1) and (prefers-color-scheme: dark) {
    path {
        fill: white;
    }
}

有一点很重要

SVG必须包含viewBox信息,这样拉伸就不会影响图形。例子:

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 300 300">