Svg `Use` Is Rendering Blank Image

I am trying to use SVGs as CSS background images, and have everything working except for importing external files with use.

Here is what I have:

CSS and HTML:

.shape1 {
  background: url("shapes/shape1.svg") no-repeat;
}

<div class="shape1"></div>

Then the shapes/shape1.svg file:

<svg viewBox="0 0 100 200" xmlns="">
  <path d="
    M 10 10
    l 0 180
    " fill="none" stroke="#000" stroke-width="1px"/>

  <use href="parts/part1.svg#build"/>
</svg>

It references the parts/part1.svg file, which contains this:

<svg viewBox="0 0 100 200" xmlns="">  
  <defs>
    <path id="build" d="
      M 90 10
      l 0 180
      " fill="none" stroke="#000" stroke-width="1px"/>
  </defs>
</svg>

However, when I render everything, it only displays one line, not two.

I've tried a few things. I've tried removing the defs and just loading directly, like this:

<svg viewBox="0 0 100 200" xmlns="">
  <path d="
    M 10 10
    l 0 180
    " fill="none" stroke="#000" stroke-width="1px"/>

  <use href="parts/part1.svg"/>
</svg>

<svg viewBox="0 0 100 200" xmlns="">  
  <path d="
    M 90 10
    l 0 180
    " fill="none" stroke="#000" stroke-width="1px"/>
</svg>

I've also tried messing with the file paths. My directory structure is this:

index.html
shapes/
shapes/shape1.svg
parts/
parts/part1.svg

I've tried ../parts/part1.svg, etc.. Also, I am running this directly from the filesystem, so the path is: file:///Users/me/Desktop/test/index.html. I am getting no errors in the web console. Any help would be appreciated!

I am on Chrome and only care about this working on Chrome for now.

1

1 Answer

When SVG is used as an image the SVG file must be self-contained for privacy reasons.

So shape1.svg cannot access anything outside itself. You'd have to embed part1.svg into shape1.svg.

Alternatively don't use SVG as a background image, embed it via an object or iframe tag or have it inline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest