CSS 如何在元素的 :before 伪元素上添加 svg 作为内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45691117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a svg as content on :before pseudo element of an element?
提问by Francisco Romero
I am trying to use a svg inside content of :before
pseudo element.
我正在尝试在:before
伪元素的内容中使用 svg 。
For this purpose, I am following this question: Is there a way to use SVG as content in a pseudo element :before or :afterbut I cannot make it work.
为此,我关注这个问题:是否有办法将 SVG 用作伪元素中的内容 :before 或 :after但我无法使其工作。
I just have a simple SVG:
我只有一个简单的 SVG:
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
And here is what I have tried:
这是我尝试过的:
Example 1: Inserting the svg on the content attribute
示例 1:在内容属性上插入 svg
#square{
background-color: green;
width: 100px;
height: 100px;
}
#square:before{
display: block;
content: url("data:image/svg+xml;charset=UTF-8,<svg height='100' width='100'><circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' /></svg>");
background-size: 28px 28px;
height: 28px;
width: 28px;
}
<div id="square"></div>
Example 2: With base64 encoding
示例 2:使用 base64 编码
#square{
background-color: green;
width: 100px;
height: 100px;
}
#square:before{
display: block;
content: url("data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjEwMCIgd2lkdGg9IjEwMCI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNDAiIHN0cm9rZT0iYmxhY2siIHN0cm9rZS13aWR0aD0iMyIgZmlsbD0icmVkIiAvPjwvc3ZnPg==");
background-size: 28px 28px;
height: 28px;
width: 28px;
}
<div id="square"></div>
As you can see, any of those examples does not work so I am sure that I am missing something.
如您所见,这些示例中的任何一个都不起作用,因此我确信我遗漏了一些东西。
What I am doing wrong?
我做错了什么?
Thanks in advance!
提前致谢!
回答by Niloct
Seems like the SVG
tag needed more attributes.
似乎SVG
标签需要更多属性。
#square{
background-color: green;
width: 100px;
height: 100px;
}
#square:before{
display: block;
content: url("data:image/svg+xml;charset=UTF-8, <svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='100' width='100'><circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' /></svg>");
background-size: 28px 28px;
height: 28px;
width: 28px;
}
<div id="square"></div>