如何在<symbol>中使用<defs>的SVG图像

5

我想在网页中使用 Telegram SVG 图标,并使用一个 <symbol> 标签和多个 <use> 标签进行导入。但是当我尝试下面的方法时,图标会出现问题:

<!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>

codepen.io上也有相似的问题。

为什么它会中断以及如何修复上面的代码,以允许在网页上重用SVG图标?

最终解决方案

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

即使添加了宽度和高度为零的 <svg>,它仍然占据空间,添加 position: absolute 可以解决这个问题。
1个回答

6

看起来是因为display:none导致了它的破裂。我不完全清楚为什么会这样。尝试使用其他东西而非display:none,例如position:fixed;left:-999em


我的 fill="url(#…)" 属性在 Safari 中无法正常工作。原来我在“SVG定义”元素上也设置了 display: none!以不同的方式隐藏它可以修复我的 fill 属性。 - Jackson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接