如何将内联SVG移至CSS

时间:2018-08-17 00:43:27

标签: html css svg

我有一个正在使用的内联SVG,现在想将其移动到外部文件,以便可以在其他地方使用它。

(这是一个简单的拖动图标。)

https://gist.run/?id=de197c5eb19bc35bf7f537f7aab345a8

我该怎么做?

messageCollector

我不是要自定义它,只是将其放入.css文件中以进行重用。

2 个答案:

答案 0 :(得分:1)

您可以通过创建SVG模板并在多个地方使用它来实现。

下面是示例:

svg {
  width: 40px;
  height: 100px;
}
<!-- SVG template -->
<div style="visibility: hidden; position: absolute; width: 0px; height: 0px;">
  <svg style="height:16px; width:16px;" focusable="false" viewBox="0 0 32 32">
  <symbol viewBox="0 0 18 15" id="sample">
    <path d="M14,5.5c0,1.7-1.3,3-3,3s-3-1.3-3-3s1.3-3,3-3S14,3.8,14,5.5z M21,8.5c1.7,0,3-1.3,3-3s-1.3-3-3-3s-3,1.3-3,3S19.3,8.5,21,8.5z M11,12.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S12.7,12.5,11,12.5z M21,12.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S22.7,12.5,21,12.5z M11,22.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S12.7,22.5,11,22.5z M21,22.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S22.7,22.5,21,22.5z"></path>
    </symbol>
  </svg>
</div>
          


<!-- and use it whenever you want -->
<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>

<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>

有关更多信息,请查看this文章。

答案 1 :(得分:0)

最后通过将SVG放在一个文件中来完成此工作:handle.svg:

 <?xml version="1.0" encoding="utf-8"?>
 <svg xmlns="http://www.w3.org/2000/svg" style="height:16px; width:16px;" focusable="false" viewBox="0 0 32 32">
 <path d="M14,5.5c0,1.7-1.3,3-3,3s-3-1.3-3-3s1.3-3,3-3S14,3.8,14,5.5z M21,8.5c1.7,0,3-1.3,3-3s-1.3-3-3-3s-3,1.3-3,3S19.3,8.5,21,8.5z M11,12.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S12.7,12.5,11,12.5z M21,12.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S22.7,12.5,21,12.5z M11,22.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S12.7,22.5,11,22.5z M21,22.5c-1.7,0-3,1.3-3,3s1.3,3,3,3s3-1.3,3-3S22.7,22.5,21,22.5z">
</path>
</svg>

然后像这样使用它:

 <img style="height:16px;width:16px;" src="/assets/images/grippy.svg" />