7

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

2 Answers 2

8

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

2
  • WTF! This saved my day! Thank you. I am guessing this has to do with the shadow dom somehow, and that when referencing these ideas they are somehow not referable when the display: none is being set.
    – oligofren
    Feb 15, 2017 at 20:48
  • You're welcome! Its kind weird, because this only applies to clippath in my experience. Feb 15, 2017 at 21:25
1

In my case, using only "width" and "height" equals to zero, left a void area where should be the image. However, using display:content; instead display:none; works fine, no void area and no image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.