问题
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
回答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
回答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.
来源:https://stackoverflow.com/questions/29993846/why-does-svg-use-xlinkhref-referencing-an-element-with-clip-path-not-wor