如何在CSS内容属性中更改SVG图像的颜色? [英] How do I change the colour of an SVG image in a CSS content property?

查看:2184
本文介绍了如何在CSS内容属性中更改SVG图像的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过内容属性使用SVG图片作为CSS sprite, bootstrap-style ,像这样:

  i.rectangle-image {
content:url (rectangle.svg);
}

这是我的SVG:

 < svg xmlns =http://www.w3.org/2000/svgviewBox =0 0 100 100> 
< rect x =10y =10width =80height =80/>
< / svg>

和建议的HTML:

 < div>< i class =rectangle-image>< / i> Hello,world!< / div> 

我想在我的应用程序中重新着色SVG,例如图标在某些位置显示为紫色,在其他位置显示为白色。我知道我可以做到这一点有三个不同的SVG文件(或数据URI)与填充属性设置不同的< rect> code>标签,但我想知道有没有办法通过CSS在我的HTML中这样做。



我试过添加一个填充属性到 i.rectangle-image 选择器,但不起作用。



我看过这个回答

a>并且它不是我想要的。他们建议在整个页面中嵌入SVG,如果可能,我宁愿通过CSS content 这样做。有什么想法吗?

解决方案

如果使用CSS内容工具,则基本上将图像作为SVG数据加载。出于隐私权原因,您不能使用外部CSS或javascript来影响图片的显示方式。



如果您要更改SVG数据的内容,您必须通过< object> < iframe> 标记加载它或将其放入HTML文件。 / p>

I'd like to use an SVG image as a CSS sprite through a content property, bootstrap-style, like so:

i.rectangle-image {
  content: url(rectangle.svg);
}

and here's my SVG:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"/>
</svg>

and proposed HTML:

<div><i class="rectangle-image"></i> Hello, world!</div>

I'd like to be able to re-colour the SVG in my application, for example to have the icon appear purple in some locations, and white in others. I know I can accomplish this by having three different SVG files (or data URIs) with the fill attribute set differently on the <rect> tag, but I'm wondering if there's a way for me to do this through CSS in my HTML?

I've tried adding a fill attribute to the i.rectangle-image selector, but that doesn't work.

I've looked at this answer and it's not quite what I want. They suggest embedding SVG throughout the page, and I'd prefer to do this via CSS content if possible. Any thoughts? Am I out of luck?

解决方案

If you use the CSS content facility you're loading the SVG data basically as an image. For privacy reasons you can't affect how the image is displayed using external CSS or javascript.

If you want to change the contents of SVG data you'd either have to load it via an <object> or <iframe> tag or put it inline in the HTML file.

这篇关于如何在CSS内容属性中更改SVG图像的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆