I am trying to use a svg inside content of :before
pseudo element.
For this purpose, I am following this question: Is there a way to use SVG as content in a pseudo element :before or :after but I cannot make it work.
I just have a simple 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
#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
#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!
SVG content can be added using these pseudo-elements by following the methods described below: Method 1: Using the background-image property: The background-image property is used to set one or more background images to an element.
Using SVG as a background-image Similarly easy to using SVG as an img, you can use it in CSS as a background-image .
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
The fill property in CSS is for filling in the color of a SVG shape.
Seems like the SVG
tag needed more attributes.
#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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With