Why does svg <use xlink:href="#"/> referencing an element with clip-path not work?

Betsy Dupuis picture Betsy Dupuis · May 1, 2015 · Viewed 13.5k times · Source

When implementing an SVG sprite, an <svg> element is created and svg elements are referenced via the <use> element. The containing <svg> element is then hidden using style="display: none;"

The clip-Path attribute does not render, but the path does. This leaves my path looking different from how I want it to.

How do I use an svg <use xlink:href="#"/> referencing an element with clip-path?

I used grunt-svg-store to create my svg sprite, but have simplified this example for Q&A format https://css-tricks.com/svg-sprites-use-better-icon-fonts/

<svg id="svg-test" style="display: none;">
  <clipPath id="my-clip-1">
    <circle id="circle-1" cx="50" cy="50" r="50" />
  </clipPath>
  <path id="svg-test-reference" clip-path="url(#my-clip-1)" d="M10-39.288h80v80H10z" />
</svg>

<!-- Reference SVG <path> by ID with Use -->

<svg class="svg-item" viewBox="0 0 100 100">
  <use xlink:href="#svg-test-reference" />
</svg>

Live example on Codepen.io

Answer

Betsy Dupuis picture Betsy Dupuis · May 1, 2015

Use <svg style="width:0; height:0;"> instead of <svg style="display: none;"> to hide the sprite.

<!-- SVG element  -->

<svg id="svg-test" style="width:0; height:0;">
  <clipPath id="my-clip-1">
    <circle id="circle-1" cx="50" cy="50" r="50" />
  </clipPath>
  <path id="svg-test-reference" clip-path="url(#my-clip-1)" d="M10-39.288h80v80H10z" />
</svg>

<!-- Reference SVG <path> by ID with Use -->

<svg class="svg-item" viewBox="0 0 100 100">
  <use xlink:href="#svg-test-reference" />
</svg>

Live example on Codepen.io