使用CSS对SVG内容进行着色的URL

12

我有一个按钮设置如下:

<button class="buttonclass"><i class="iconclass plus-icon"></i></button>

我的CSS类看起来像这样:

.buttonclass {
  width: 30px;
  height: 30px;
  text-align: center;
  position: relative;
  border-radius: 20px;
  background-color: #1DBE60
}

.iconclass {
  width: 20px;
  height: 20px;
  margin: 7.5px;
}

.buttonclass .iconclass {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.plus-icon {
  content: url(http://uxrepo.com/static/icon-sets/mfg-labs/svg/plus.svg);
}
如何使用CSS更改SVG中的“加号图标”的颜色?我尝试了添加填充类、颜色类、背景类等方法,但都不起作用。以下是一个示例链接:http://plnkr.co/edit/6fLYQlpFmDdf7aWenBtp?p=preview

1
当使用SVG作为背景图像时,这是不可能的。https://css-tricks.com/using-svg/ - CBroe
通常情况下,您会使用图标字体而不是SVG。 - Brian Glaz
@CBroe,使用SVG作为图标的最佳方法是什么?我必须使用内联SVG吗?我能否通过使用类来使用我的当前设置的任何方式? - developthewebz
@BrianGlaz我有我自己的一组自定义图标,我正在使用它们作为svg...那么使用它们的更好方法是什么? - developthewebz
你可以有两个加号图标,一个是每种颜色一个,然后在它们之间进行切换。或者你可以通过对象标签加载你的SVG文件,然后将CSS放在SVG文件本身中。 - Robert Longson
显示剩余2条评论
3个回答

5

如果您愿意添加一个额外的类(用于加号图标的颜色),那么这里有一个仅使用CSS的解决方案,使用currentColor CSS变量:

.buttonclass {
  width: 30px;
  height: 30px;
  text-align: center;
  position: relative;
  border-radius: 20px;
  background-color: #1DBE60
}

.iconclass {
  width: 20px;
  height: 20px;
  margin: 7.5px;
}

.buttonclass .iconclass {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.plus-icon {
background-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><rect x="0" y="0" width="8" height="8" fill="rgb(29,190,96)" /><rect x="0" y="12" width="8" height="8" fill="rgb(29,190,96)" /><rect x="12" y="0" width="8" height="8" fill="rgb(29,190,96)" /><rect x="12" y="12" width="8" height="8" fill="rgb(29,190,96)" /></svg>');
background-color: currentColor;
border: 1px solid rgb(29,190,96);
border-radius: 15px;
}

.white {
color: rgb(255,255,255);
}

.yellow {
color: rgb(255,255,0);
}

.green {
color: rgb(0,255,0);
}
<button class="buttonclass"><i class="iconclass plus-icon white"></i></button>
<button class="buttonclass"><i class="iconclass plus-icon yellow"></i></button>
<button class="buttonclass"><i class="iconclass plus-icon green"></i></button>


0

我最初来到这里是为了寻找一种给SVG图标上色的方法。最受欢迎的答案并没有帮助我,所以在经过一些谷歌搜索后,我发现了这个有趣的codepen

长话短说,我使用了以下CSS来给我的SVG图标上色:

.plus-icon {
    -webkit-mask: url('../images/plus.svg') no-repeat 50% 50%;
    mask: url('../images/plus.svg') no-repeat 50% 50%;
    -webkit-mask-size: cover;
    mask-size: cover;
}

.white {
    background-color: rgb(255,255,255);
}

更新:

不支持IE浏览器。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接