Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to <use> SVG Image with <defs> Inside <symbol>

Tags:

html

svg

I want to import Telegram SVG icon into a a webpage with a <symbol> tag and multiple <use> tags. The problem is that the icon gets broken when I try the approach below:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    Here is an icon:

    <!-- SVG Definition -->

    <svg style="display: none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <linearGradient id="b" x1="0.6667" y1="0.1667" x2="0.4167" y2="0.75">
          <stop stop-color="#37aee2" offset="0"/>
          <stop stop-color="#1e96c8" offset="1"/>
        </linearGradient>
        <linearGradient id="w" x1="0.6597" y1="0.4369" x2="0.8512" y2="0.8024">
          <stop stop-color="#eff7fc" offset="0"/>
          <stop stop-color="#fff" offset="1"/>
        </linearGradient>
      </defs>  
      <symbol id="telegram-icon" viewBox="0 0 240 240">
        <circle cx="120" cy="120" r="120" fill="url(#b)"/>
        <path fill="#c8daea" d="m98 175c-3.8876 0-3.227-1.4679-4.5678-5.1695L82 132.2059 170 80"/>
        <path fill="#a9c9dd" d="m98 175c3 0 4.3255-1.372 6-3l16-15.558-19.958-12.035"/>
        <path fill="url(#w)" d="m100.04 144.41 48.36 35.729c5.5185 3.0449 9.5014 1.4684 10.876-5.1235l19.685-92.763c2.0154-8.0802-3.0801-11.745-8.3594-9.3482l-115.59 44.571c-7.8901 3.1647-7.8441 7.5666-1.4382 9.528l29.663 9.2583 68.673-43.325c3.2419-1.9659 6.2173-0.90899 3.7752 1.2584"/>
      </symbol>
    </svg>

    <!-- SVG Usage -->

    <svg><use href="#telegram-icon"></use></svg>
    <br/>
    <a href="https://commons.wikimedia.org/wiki/File:Telegram_logo.svg">Source of the image</a>
  </body>
</html>

Also on codepen.io.

Why does it get broken and how to fix the code above to allow reuse of the SVG icon on a webpage?

Final Solution

<svg style="width: 0; height: 0; position: absolute;"...>

Even after adding zeroed width and height <svg> still was taking place, adding position: absolute solved this problem.

like image 375
ilyaigpetrov Avatar asked Sep 07 '25 10:09

ilyaigpetrov


1 Answers

It seems like display:none is what causes it to break. I'm not 100% clear why. Try using something other than display:none, for example position:fixed;left:-999em.

like image 148
greim Avatar answered Sep 09 '25 23:09

greim