Russel Riehle Russel Riehle - 3 months ago 12
CSS Question

Why my SVG calling doesn't work?

I'm studying SVG files (beginning) but I can't make my SVG appear when I set

<defs>
tag!

I mean.. If I call the SVG directly it works properly.

Like this:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="163.514px" height="263.514px" viewBox="0 0 163.514 263.514" enable-background="new 0 0 163.514 263.514"
xml:space="preserve">
<g>
<rect class="bosta1" y="55.406" fill="#E8CF1E" stroke="#000000" stroke-miterlimit="10" width="163.514" height="137.838"/>
<rect class="bosta2" x="62.162" fill="#E42326" stroke="#000000" stroke-miterlimit="10" width="44.811" height="263.514"/>
</g>
</svg>


Fiddle: https://jsfiddle.net/sz0bkbdm/

But if I try to use refs I can't make the rects visible.

Like this:

<svg version="1.1" id="mySvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="163.514px" height="263.514px" viewBox="0 0 163.514 263.514" enable-background="new 0 0 163.514 263.514"
xml:space="preserve">

<defs>
<g>

<rect class="ret1" y="55.406" stroke-miterlimit="10" width="163.514" height="137.838"/>
<rect class="ret2" x="62.162" stroke-miterlimit="10" width="44.811" height="263.514"/>

</g>
</defs>
</svg>

MY CONTENT

<svg>
<use xlink:href="#mySvg"></use>
</svg>


Fiddle: https://jsfiddle.net/g1hdLy82/

Answer

You can try this:

<svg version="1.1" id="mySvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="163.514px" height="263.514px" viewBox="0 0 163.514 263.514" enable-background="new 0 0 163.514 263.514"
     xml:space="preserve">
<defs>   
    <rect id="ret1" y="55.406" stroke-miterlimit="10" width="163.514" height="137.838"/>
    <rect id="ret2" x="62.162" stroke-miterlimit="10" width="44.811" height="263.514"/>
</defs>
</svg>

MY CONTENT

<svg>
    <use xlink:href="#ret1"></use>
    <use xlink:href="#ret2"></use>
</svg>

and the css is:

#mySvg { width:100px; height:auto; }
#ret1 { fill:green; stroke:red; }
#ret2 { fill:blue; stroke:white; }
Comments