CSS 如何更改 svg 元素的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22252472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:02:58  来源:igfitidea点击:

How to change the color of an svg element?

csssvg

提问by Barbara

I want to use this technique http://css-tricks.com/svg-fallbacks/and change the svg color but so far I haven't been able to do so. I put this in the css but my image is always black, no matter what. My code:

我想使用这种技术http://css-tricks.com/svg-fallbacks/并更改 svg 颜色,但到目前为止我还没有这样做。我把它放在 css 中,但无论如何我的图像总是黑色的。我的代码:

.change-my-color {
  fill: green;
}
<svg>
    <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src="ppngfallback.png" />
</svg>

采纳答案by helderdarocha

You can't change the color of an image that way. If you load SVG as an image, you can't change how it is displayed using CSS or Javascript in the browser.

您不能以这种方式更改图像的颜色。如果您将 SVG 作为图像加载,则无法在浏览器中使用 CSS 或 Javascript 更改其显示方式。

If you want to change your SVG image, you have to load it using <object>, <iframe>or using <svg>inline.

如果你想改变你的SVG图像,你必须用它来装载<object><iframe>或使用<svg>在线。

If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.

如果您想使用页面中的技术,您需要 Modernizr 库,您可以在其中检查 SVG 支持并有条件地显示或不显示后备图像。然后,您可以内联 SVG 并应用您需要的样式。

See :

看 :

#time-3-icon {
   fill: green;
}

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}
<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206
 C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161
 C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505
 c-37.093,6.938-124.97,21.35-134.613,21.35c-13.808,0-25-11.192-25-25c0-9.832,14.79-104.675,21.618-143.081
 c0.274-1.542,1.615-2.669,3.181-2.669h0.008c1.709,0,3.164,1.243,3.431,2.932l18.933,119.904L382.816,265.785z"/>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

You can inline your SVG, tag your fallback image with a class name (my-svg-alternate):

您可以内联您的 SVG,使用类名 ( my-svg-alternate)标记您的后备图像:

<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

And in CSS use the no-svgclass from Modernizr (CDN: http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js) to check for SVG support. If there is no SVG support the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (display: none):

在 CSS 中使用no-svgModernizr 中的类(CDN:http: //ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js)来检查 SVG 支持。如果没有 SVG 支持,SVG 块将被忽略并显示图像,否则图像将从 DOM 树中删除 ( display: none):

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}

Then you can change the color of your inlined element:

然后您可以更改内联元素的颜色:

#time-3-icon {
   fill: green;
}

回答by Manish Menaria

2020 answer

2020 答案

CSS Filter works on all current browsers

CSS 过滤器适用于所有当前浏览器

To change any SVGs color

更改任何 SVG 颜色

  1. Add the SVG image using an <img>tag.
  1. 使用<img>标签添加 SVG 图像。
<img src="dotted-arrow.svg" class="filter-green"/>
  1. To filter to a specific color, use the following Codepen(Click Here to open codepen)to convert a hex color code to a CSS filter:
  1. 要过滤到特定颜色,请使用以下Codepen(单击此处打开 codepen)将十六进制颜色代码转换为 CSS 过滤器:

For example, output for #00EE00is

例如,输出#00EE00

filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%);
  1. Add the CSS filterinto this class.
  1. 将 CSS 添加filter到这个类中。
    .filter-green{
        filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);
    }

回答by sushant047

To change the color of any SVG you can directly change the svg code by opening the svg file in any text editor. The code may look like the below code

要更改任何 SVG 的颜色,您可以通过在任何文本编辑器中打开 svg 文件直接更改 svg 代码。代码可能类似于下面的代码

<?xml version="1.0" encoding="utf-8"?>
    <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <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="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
    <g>
        <path d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
            C181.113,454.921,171.371,464.663,161.629,474.404z"/>
    /*Some more code goes on*/
    </g>
    </svg>

You can observe that there are some XML tags like path, circle, polygon etc. There you can add your own color with help of style attribute. Look at the below example

您可以观察到有一些 XML 标记,如路径、圆、多边形等。在那里您可以借助style 属性添加自己的颜色。看下面的例子

<path style="fill:#AB7C94;" d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
                C181.113,454.921,171.371,464.663,161.629,474.404z"/>

Add the style attribute to all the tags so that you can get your SVG of your required color

将 style 属性添加到所有标签,以便您可以获得所需颜色的 SVG

回答by Yonatan Ayalon

Added a test page - to color SVG via Filter settings:

添加了一个测试页面 - 通过过滤器设置为 SVG 着色:

E.G filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg)

例如 filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg)

Upload & Color your SVG - Jsfiddle

上传和着色你的 SVG - Jsfiddle

Took the idea from: https://blog.union.io/code/2017/08/10/img-svg-fill/

想法来自:https: //blog.union.io/code/2017/08/10/img-svg-fill/

回答by Biskrem Muhammad

Only SVG with path information. you can't do that to the image.. as the path you can change stroke and fill information and you are done. like Illustrator

只有带有路径信息的 SVG。你不能对图像这样做..作为你可以改变笔触和填充信息的路径,你就完成了。喜欢插画师

so: via CSS you can overwrite path fillvalue

所以:通过 CSS 你可以覆盖路径fill

path { fill: orange; }

but if you want more flexible way as you want to change it with a text when having some hovering effect going on.. use

但是如果你想要更灵活的方式,因为你想在有一些悬停效果时用文本改变它......使用

path { fill: currentcolor; }

body {
  background: #ddd;
  text-align: center;
  padding-top: 2em;
}

.parent {
  width: 320px;
  height: 50px;
  display: block;
  transition: all 0.3s;
  cursor: pointer;
  padding: 12px;
  box-sizing: border-box;
}

/***  desired colors for children  ***/
.parent{
  color: #000;
  background: #def;
}
.parent:hover{
  color: #fff;
  background: #85c1fc;
}

.parent span{
  font-size: 18px;
  margin-right: 8px;
  font-weight: bold;
  font-family: 'Helvetica';
  line-height: 26px;
  vertical-align: top;
}
.parent svg{
  max-height: 26px;
  width: auto;
  display: inline;
}

/****  magic trick  *****/
.parent svg path{
  fill: currentcolor;
}
<div class='parent'>
  <span>TEXT WITH SVG</span>
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" viewBox="0 0 32 32">
<path d="M30.148 5.588c-2.934-3.42-7.288-5.588-12.148-5.588-8.837 0-16 7.163-16 16s7.163 16 16 16c4.86 0 9.213-2.167 12.148-5.588l-10.148-10.412 10.148-10.412zM22 3.769c1.232 0 2.231 0.999 2.231 2.231s-0.999 2.231-2.231 2.231-2.231-0.999-2.231-2.231c0-1.232 0.999-2.231 2.231-2.231z"></path>
</svg>
</div>

回答by Felix Hagspiel

the easiest way would be to create a font out of the SVG using a service like https://icomoon.io/app/#/selector such. upload your SVG, click "generate font", include font files and css into your side and just use and style it like any other text. I always use it like this because it makes styling much easier.

最简单的方法是使用https://icomoon.io/app/#/select等服务从 SVG 中创建字体。上传您的 SVG,单击“生成字体”,将字体文件和 css 包含在您的一侧,然后像任何其他文本一样使用和设置样式。我总是这样使用它,因为它使造型更容易。

EDIT:As mentioned in the articlecommented by @CodeMouse92 icon fonts mess up screen readers (and are possibly bad for SEO). So rather stick to the SVGs.

编辑:正如@CodeMouse92 评论的文章中提到的那样,图标字体弄乱了屏幕阅读器(并且可能对 SEO 不利)。所以宁愿坚持使用SVG。

回答by cydoc

You can change SVG coloring with css if you use some tricks. I wrote a small script for that.

如果您使用一些技巧,您可以使用 css 更改 SVG 颜色。我为此写了一个小脚本。

  • go through a list of elements which do have an svg image
  • load the svg file as xml
  • fetch only svg part
  • change color of path
  • replace src with the modified svg as inline image
  • 浏览具有 svg 图像的元素列表
  • 将 svg 文件加载为 xml
  • 只获取 svg 部分
  • 改变路径颜色
  • 将 src 替换为修改后的 svg 作为内嵌图像
$('img.svg-changeable').each(function () {
  var $e = $(this);
  var imgURL = $e.prop('src');

  $.get(imgURL, function (data) {
    // Get the SVG tag, ignore the rest
    var $svg = $(data).find('svg');

    // change the color
    $svg.find('path').attr('fill', '#000');

    $e.prop('src', "data:image/svg+xml;base64," + window.btoa($svg.prop('outerHTML')));
  });

});

the code above might not be working correctly, I've implemented this for elements with an svg background image which works nearly similar to this. But anyway you have to modify this script to fit your case. hope it helped.

上面的代码可能无法正常工作,我已经为具有 svg 背景图像的元素实现了这一点,其工作方式几乎与此类似。但无论如何,您必须修改此脚本以适合您的情况。希望它有所帮助。

回答by Sethu Sathyan

To simply change the color of the svg :

简单地改变 svg 的颜色:

Go to the svg file and under styles, mention the color in fill.

转到 svg 文件,在样式下,提及填充颜色。

<style>.cls-1{fill:#FFFFFF;}</style>

回答by Michael Philips

Target the path within the svg:

定位 svg 中的路径:

<svg>
   <path>....
</svg>

You can do inline, like:

您可以进行内联,例如:

<path fill="#ccc">

Or

或者

svg{
   path{
        fill: #ccc

回答by vsync

SVG maskon a box element with a background colorwill result:

带有背景颜色的框元素上的SVG蒙版将导致:

.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;
  -webkit-mask-image: url(https://image.flaticon.com/icons/svg/89/89139.svg);
  mask-image: url(hhttps://image.flaticon.com/icons/svg/89/89139.svg);
  animation: 1s frames infinite ease;
}

@keyframes frames {
  50% { background:red;  }
}
<i class="icon icon-bike" style="--size:150px"></i>



Note - SVG masks are not supported in Internet Explorerbrowsers

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