DEV Community

Cover image for How to put SVG inside pseudo elements in CSS?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to put SVG inside pseudo elements in CSS?

Originally posted here!

To put SVG as the content inside pseudo-elements like :before and :after, you can use the url() function in the CSS and pass the link to the SVG file as a string to the function.

/* Put Svg in Pseudo element ✅ */
div:after {
  content: url("path-to-my-svg.svg");
}
Enter fullscreen mode Exit fullscreen mode

For example, let use a real SVG icon to understand. Check out the SVG which we will be using for the example.

Now in the :after or :before pseudo elements for a p (paragragh) element, you can use it like this,

p:before {
  content: url("https://upload.wikimedia.org/wikipedia/commons/9/99/Leo.svg");
}
Enter fullscreen mode Exit fullscreen mode

That's it! 🔥

See the above code live in JSBin

Feel free to share if you found this useful 😃.


Top comments (1)

Collapse
 
d7460n profile image
D7460N • Edited

What if you wanted to inline the SVG?

Such as

div::after {
  content: "<svg
  xmlns="http://www.w3.org/2000/svg"
  width="24"
  height="24"
  viewBox="0 0 24 24"
  fill="none"
  stroke="currentColor"
  stroke-width="2"
  stroke-linecap="round"
  stroke-linejoin="round"
>
  <polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6" />
  <line x1="8" y1="2" x2="8" y2="18" />
  <line x1="16" y1="6" x2="16" y2="22" />
</svg>";
}
Enter fullscreen mode Exit fullscreen mode