Search code examples
csssvgpseudo-element

Is there a way to use SVG as content in a pseudo element ::before or ::after


I would like to use ::before to place SVG images before some selected elements:

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

Above code just displays the plaintext.
I checked the spec and there seem to be some restrictions on what content can be. CSS content property solution is preferable.


Solution

  • Yes you can! Just tested this and it works great, this is awesome!

    #test::before {
      content: url(path/to/your.svg);
      width: 200px;
      height: 200px;
    }
    

    Or if you prefer to put the SVG directly in the CSS:

    #test::before {
      content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='100' cy='50' r='40' stroke='black' stroke-width='2' fill='red'/%3E%3Cpolyline points='20,20 40,25 60,40 80,120 120,140 200,180' style='fill:none;stroke:black;stroke-width:3'/%3E%3C/svg%3E ");
      width: 200px;
      height: 200px;
    }
    <div id="test"></div>

    SVG URL encoder to format your own SVGs as shown here.