html - 是否可以引用一次 svg 文件,然后多次使用它?

标签 html css svg

所以不用这些:

<svg class="icon-user">
    <use href="LONGFILENAME.svg#icon-user">
    </use>
</svg>

<svg class="icon-user2">
    <use href="LONGFILENAME.svg#icon-user2">
    </use>
</svg>

我想让我的 SVG 在某种程度上是全局的或以某种方式被引用,并且只是像这样使用我的代码:

<svg class="icon-user">
    <use href="#icon-user">
    </use>
</svg>

<svg class="icon-user2">
    <use href="#icon-user2">
    </use>
</svg>

这可能吗?

最佳答案

<use> , href可以引用:

A URL reference to an element/fragment within an SVG document to be cloned.

因此,您可以包含一个包含多个 SVG 的“定义”文件,并在整个文档中引用它们。

#svgdefs {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

.icon {
  width: 2em;
  height: 2em;
  fill: gray;
}

.icon-star {
  fill: orange;
}

.icon-star-tomato {
  fill: tomato;
}
<svg aria-hidden="true" id="svgdefs" version="2" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <symbol id="icon-lock" viewBox="0 0 32 32">
      <title>lock</title>
      <path d="M15 21.915v0c-0.583-0.206-1-0.762-1-1.415 0-0.828 0.672-1.5 1.5-1.5s1.5 0.672 1.5 1.5c0 0.653-0.417 1.209-1 1.415v2.594c0 0.263-0.224 0.491-0.5 0.491-0.268 0-0.5-0.22-0.5-0.491v-2.594zM8 14v0 0c-1.658 0.005-3 1.34-3 3.009v9.981c0 1.662 1.346 3.009 3.009 3.009h14.982c1.662 0 3.009-1.337 3.009-3.009v-9.981c0-1.659-1.341-3.005-3-3.009v-3.501c0-4.142-3.366-7.499-7.5-7.499-4.142 0-7.5 3.357-7.5 7.499v3.501zM11 14v-3.499c0-2.492 2.015-4.501 4.5-4.501 2.48 0 4.5 2.015 4.5 4.501v3.499h-9z"></path>
    </symbol>
    <symbol id="icon-star" viewBox="0 0 30 32">
      <title>star</title>
      <path d="M29.714 11.554c0 0.321-0.232 0.625-0.464 0.857l-6.482 6.321 1.536 8.929c0.018 0.125 0.018 0.232 0.018 0.357 0 0.464-0.214 0.893-0.732 0.893-0.25 0-0.5-0.089-0.714-0.214l-8.018-4.214-8.018 4.214c-0.232 0.125-0.464 0.214-0.714 0.214-0.518 0-0.75-0.429-0.75-0.893 0-0.125 0.018-0.232 0.036-0.357l1.536-8.929-6.5-6.321c-0.214-0.232-0.446-0.536-0.446-0.857 0-0.536 0.554-0.75 1-0.821l8.964-1.304 4.018-8.125c0.161-0.339 0.464-0.732 0.875-0.732s0.714 0.393 0.875 0.732l4.018 8.125 8.964 1.304c0.429 0.071 1 0.286 1 0.821z"></path>
    </symbol>
  </defs>
</svg>

<svg class="icon icon-lock"><use href="#icon-lock"></use></svg>
<svg class="icon icon-star"><use href="#icon-star"></use></svg>
<svg class="icon icon-star"><use href="#icon-star"></use></svg>
<svg class="icon icon-star icon-star-tomato"><use href="#icon-star"></use></svg>

关于html - 是否可以引用一次 svg 文件,然后多次使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50124658/

相关文章:

CSS 选择器 : parent and child element

css - 如何将 -webkit-clip-path 设置为属性?

html - 如何在我的 HTML 中链接 .svg 文件?

html - Flexbox div 不占用整个宽度

html - 匹配两个 div 的渐变(如果它们具有不同的宽度)

html - 使用无序列表将所有内容放在一行中

javascript - CSS 水平滚动,如何将 "below"定位在 "right"之前?

html - 当用户点击展开所有分组 ui 网格时拦截

html - 将三个 div 类放入同一行

javascript - 使用 SVG 并应用样式表中的 CSS