有没有办法在伪元素 ::before 或 ::after 中使用 SVG 作为内容

有没有办法在伪元素 ::before 或 ::after 中使用 SVG 作为内容

问题描述:

我想在某些选定元素之前放置一些 SVG 图像.我正在使用 jQuery,但这无关紧要.

I want to place some SVG images before some selected elements. I am using jQuery but that is irrelevant.

我希望 ::before 元素为:

#mydiv::before {
  content: '<svg ... code here</svg>';
  display: block;
  width: 22px;
  height: 10px;
  margin: 10px 5px 0 10px;
}

如果我像上面那样做,它只会显示字符串.我检查了规格,似乎对可以包含的内容有一些限制.是否有解决此限制的方法?只有 CSS content 与我的问题相关.

If I do it as shown above, it just display the string. I checked the specs and there seems to be some restrictions on what content can be. Is there a work around to this restriction? Only CSS content is relevant to my question.

是的,你可以!刚刚测试了这个,效果很好,这太棒了!它仍然不适用于 html,但适用于 svg.

Yes you can! Just tested this and it works great, this is awesome! It still doesn't work with html, but it does with svg.

在我的 index.html 中有:

In my index.html I have:

<div id="test" style="content: url(test.svg); width: 200px; height: 200px;"></div>

我的 test.svg 看起来像这样:

And my test.svg looks like this:

<svg xmlns="http://www.w3.org/2000/svg">
   <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
   <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3"/>
</svg>