通过img标签引用SVG时,如何控制其fill和stroke属性并实现复用?
如何通过CSS控制外部SVG的fill/stroke属性(无需直接嵌入HTML)
以下是几种无需重复复制SVG代码,就能用CSS控制其填充、描边颜色的方案:
方案1:使用SVG Sprite(最推荐)
将所有SVG图标集中到一个sprite文件中,通过<use>标签引用,既能复用又能正常控制样式:
- 创建SVG Sprite文件(比如
icons-sprite.svg),用<symbol>包裹每个图标并设置唯一ID:
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="person-fill" viewBox="0 0 16 16"> <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4Zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10Z"/> </symbol> <!-- 其他图标同样用<symbol>添加即可 --> </svg>
- 在HTML中引用目标图标:
<svg class="user-icon" title="User profile"> <use href="/images/svg/icons-sprite.svg#person-fill"></use> </svg>
- 直接用CSS控制样式:
.user-icon { fill: #ff4500; /* 设置填充色 */ stroke: #000; /* 设置描边色 */ width: 16px; height: 16px; }
方案2:CSS Mask + background-image(适合简单场景)
利用currentColor让SVG继承父元素颜色,结合mask实现颜色控制(你的Bootstrap SVG已经自带fill="currentColor",刚好适配):
.user-icon { width: 16px; height: 16px; color: #2ecc71; /* 这里的颜色会被SVG的currentColor继承 */ /* Mask方式(支持透明背景) */ -webkit-mask-image: url('/images/svg/person-fill.svg'); mask-image: url('/images/svg/person-fill.svg'); -webkit-mask-size: contain; mask-size: contain; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; background-color: currentColor; }
方案3:使用<object>标签引用
通过<object>加载SVG,可跨文档控制样式,但需要注意作用域:
- HTML引用:
<object class="user-icon" data="/images/svg/person-fill.svg" type="image/svg+xml" title="User profile"></object>
- 在SVG文件内添加样式类或CSS变量:
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" class="bi bi-person" viewBox="0 0 16 16"> <style> .icon-fill { fill: var(--icon-color); } </style> <path class="icon-fill" d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4Zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10Z"/> </svg>
- 在HTML的CSS中设置变量:
.user-icon { --icon-color: #9b59b6; }
内容的提问来源于stack exchange,提问作者Goran
相关产品推荐
相关产品推荐

