Change SVG fill color in :before or :after CSS

£可爱£侵袭症+ 提交于 2019-12-18 11:06:56

问题


I have a SVG graphic put like this:

a::before { content: url(filename.svg); }

When I hover over the tag, I really want the SVG to change the fill color, without loading a new SVG file, as I have now:

a:hover::before { content: url(filename_white.svg); }

Is this possible to achieve using JavaScript, jQuery or just pure CSS that I am not aware of?

Thanks.


回答1:


Using the content property generates (non-exposed) markup functionally equvialent to an svg in an <img> element.

You cannot apply style to elements inside the svg document because:

  1. styles are not allowed to cascade across documents
  2. when using <img> (or content, or any css image property that references svg) the svg document is not exposed by the browsers due to security concerns

Similar questions, but for background-image here and here.

So, to do what you want you must get around the two points above somehow. There are various options for doing that, e.g using inline svg, using filters (applied to the <img>) or generating different svg files (or data URIs), as in your question.




回答2:


The accepted answer is incorrect, this is actually possible by applying a workaround with an SVG mask and background-color:

p:after {
  width: 48px;
  height: 48px;
  display: inline-block;
  content: '';
  -webkit-mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
  mask: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
  -webkit-mask-size: cover;
  mask-size: cover;
}

.red:after {
  background-color: red;
}

.green:after {
  background-color: green;
}

.blue:after {
  background-color: blue;
}
<p class="red">red heart</p>
<p class="green">green heart</p>
<p class="blue">blue heart</p>

You're not actually modifying the SVG DOM itself, you're just changing the background color. That way, you could even use images or gradients as background.


Update

As MisterJ mentioned, this feature is sadly not widely supported.

After three years, the support for prefixed use has risen to 93%.



来源:https://stackoverflow.com/questions/21509982/change-svg-fill-color-in-before-or-after-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!