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

16,251

Solution 1

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

Solution 2

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.

Share:
16,251
Betsy Dupuis
Author by

Betsy Dupuis

I am a front-end developer and designer.

Updated on June 05, 2022

Comments

  • Betsy Dupuis
    Betsy Dupuis almost 2 years

    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

  • oligofren
    oligofren about 7 years
    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.
  • Betsy Dupuis
    Betsy Dupuis about 7 years
    You're welcome! Its kind weird, because this only applies to clippath in my experience.