您可以改用<use> 元素。
给你的路径元素一个唯一的 id 并去掉所有的填充属性:
Svg 标记
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="500px" height="500px" >
<path id="icon"
d="M6,6A2,2,0,0,1,8,4,1,1,0,0,0,8,2,4,4,0,0,0,4,6V9a2,2,0,0,1-2,2,1,1,0,0,0,0,2,2,2,0,0,1,2,2v3a4,4,0,0,0,4,4,1,1,0,0,0,0-2,2,2,0,0,1-2-2V15a4,4,0,0,0-1.38-3A4,4,0,0,0,6,9Zm16,5a2,2,0,0,1-2-2V6a4,4,0,0,0-4-4,1,1,0,0,0,0,2,2,2,0,0,1,2,2V9a4,4,0,0,0,1.38,3A4,4,0,0,0,18,15v3a2,2,0,0,1-2,2,1,1,0,0,0,0,2,4,4,0,0,0,4-4V15a2,2,0,0,1,2-2,1,1,0,0,0,0-2Z" />
</svg>
在 html 中使用元素
使用元素支持外部 svg 文件。
<svg>
<use href="icon.svg#icon" style="fill:red" />
</svg>
所以你不需要内联你的资产/图标svg(some legacy browsers might still have issues with external svgs在使用中引用)
示例(内联 svg 仅用于规避 CORS 问题)
<svg style="display:none" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="500px" height="500px" >
<path id="icon"
d="M6,6A2,2,0,0,1,8,4,1,1,0,0,0,8,2,4,4,0,0,0,4,6V9a2,2,0,0,1-2,2,1,1,0,0,0,0,2,2,2,0,0,1,2,2v3a4,4,0,0,0,4,4,1,1,0,0,0,0-2,2,2,0,0,1-2-2V15a4,4,0,0,0-1.38-3A4,4,0,0,0,6,9Zm16,5a2,2,0,0,1-2-2V6a4,4,0,0,0-4-4,1,1,0,0,0,0,2,2,2,0,0,1,2,2V9a4,4,0,0,0,1.38,3A4,4,0,0,0,18,15v3a2,2,0,0,1-2,2,1,1,0,0,0,0,2,4,4,0,0,0,4-4V15a2,2,0,0,1,2-2,1,1,0,0,0,0-2Z" />
</svg>
<p>
<svg>
<use href="#icon" style="fill:red" />
</svg>
<svg>
<use href="#icon" style="fill:green" />
</svg>
</p>
多个图标
当使用包含多个元素的图标时(例如在羽毛图标库中),我强烈建议将每个图标定义包装在 <symbol>element 中。
这样您就可以拥有具有不同viewBox 属性的图标:
button{
background:#999;
border:none;
font-size:2em;
border-radius:0.3em;
padding:0.3em;
color:#fff;
}
.icon-use{
display: inline-block;
width:1em;
height:1em;
font-size:1em;
color:inherit;
vertical-align:-0.1em;
}
.icon-green{
color:green
}
<button type='button'>
Download
<svg class="icon-use">
<use href="#icon-download" />
</svg>
</button>
<button type='button'>
Download .xls
<svg class="icon-use icon-green">
<use href="#icon-download" />
</svg>
</button>
<button type='button'>
Download .docx
<svg class="icon-use" style="color:blue">
<use href="#icon-arrow" />
</svg>
</button>
<svg style="display:none" xmlns="http://www.w3.org/2000/svg">
<symbol id="icon-download" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</symbol>
<symbol id="icon-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</symbol>
</svg>