如何通过css更改单色.svg文件的颜色?

时间:2022-03-02 09:28:17

I'm using SVG icon like below and I don't want to use icon font (which I already know is easier to change color)

我正在使用下面的SVG图标,我不想使用图标字体(我已经知道更容易改变颜色)

<img src="/images/ic_play_arrow_black_24px.svg">

如何通过css更改单色.svg文件的颜色?

By default, this icons is in black color and I want to change it to green.

默认情况下,此图标为黑色,我想将其更改为绿色。

What is the best way to do it with less effort?

用更少的努力做到这一点的最佳方法是什么?

url of arrow file https://storage.googleapis.com/material-icons/external-assets/v1/icons/svg/ic_play_arrow_black_24px.svg

箭头文件的网址https://storage.googleapis.com/material-icons/external-assets/v1/icons/svg/ic_play_arrow_black_24px.svg

1 个解决方案

#1


2  

You can define the SVG in the page (although there are JS solutions for off page definitions) as a symbol or defs and then use an..ahem, use element with a class....but that may be more work than you want.

您可以在页面中定义SVG(尽管有关于页面定义的JS解决方案)作为符号或defs然后使用..ahem,使用带有类的元素....但这可能比您想要的更多工作。

svg {
  display;
  inline-block;
  width: 24px;
}
.hidden {
  display: none;
}
.red {
  fill: red;
}
.green {
  fill: green;
}
<svg class="hidden" fill="#000000" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <g id="arrow">
      <path d="M8 5v14l11-7z" />
      <path d="M0 0h24v24H0z" fill="none" />
    </g>
  </defs>
</svg>

<svg>
  <use xlink:href="#arrow" class="red" />
</svg>

<svg>
  <use xlink:href="#arrow" class="green" />
</svg>

#1


2  

You can define the SVG in the page (although there are JS solutions for off page definitions) as a symbol or defs and then use an..ahem, use element with a class....but that may be more work than you want.

您可以在页面中定义SVG(尽管有关于页面定义的JS解决方案)作为符号或defs然后使用..ahem,使用带有类的元素....但这可能比您想要的更多工作。

svg {
  display;
  inline-block;
  width: 24px;
}
.hidden {
  display: none;
}
.red {
  fill: red;
}
.green {
  fill: green;
}
<svg class="hidden" fill="#000000" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <g id="arrow">
      <path d="M8 5v14l11-7z" />
      <path d="M0 0h24v24H0z" fill="none" />
    </g>
  </defs>
</svg>

<svg>
  <use xlink:href="#arrow" class="red" />
</svg>

<svg>
  <use xlink:href="#arrow" class="green" />
</svg>