You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何SVG的color样式仅对部分SVG图形生效?

问题原因及解决办法

为什么一个生效一个不生效?

第一个SVG的<path>设置了fill="currentColor",这个属性会让路径填充色继承父元素的color属性值,所以你写的.voted svg path { color: green; }能让它变成绿色。

第二个SVG的<path>没有设置fill="currentColor",它的填充色用的是SVG默认的黑色,你的CSS只修改了color属性,没直接给fill赋值,自然不会影响它的颜色。

补充:你提到要设置stroke color(描边色),但当前代码实际是修改填充色,逻辑是一致的——要让描边继承color,得给path添加stroke="currentColor"。

怎么修复?

有两种简单方案:

方案1:修改SVG代码

给第二个SVG的<path>加上fill="currentColor",让它跟随color属性变化:

<path class="st0" d="M4.02,44.6h27.36c2.21,0,4.02,1.81,4.02,4.03v53.51c0,2.21-1.81,4.03-4.02,4.03H4.02 c-2.21,0-4.02-1.81-4.02-4.03V48.63C0,46.41,1.81,44.6,4.02,44.6L4.02,44.6z M63.06,4.46c2.12-10.75,19.72-0.85,20.88,16.48 c0.35,5.3-0.2,11.47-1.5,18.36l25.15,0c10.46,0.41,19.59,7.9,13.14,20.2c1.47,5.36,1.69,11.65-2.3,14.13 c0.5,8.46-1.84,13.7-6.22,17.84c-0.29,4.23-1.19,7.99-3.23,10.88c-3.38,4.77-6.12,3.63-11.44,3.63H55.07 c-6.73,0-10.4-1.85-14.8-7.37V51.31c12.66-3.42,19.39-20.74,22.79-32.11V4.46L63.06,4.46z" fill="currentColor"></path>

方案2:修改CSS直接设置fill

不想改动SVG代码的话,直接在CSS里给path添加fill: green;:

.voted svg path {
    color: green;
    fill: green;
}

如果你的真实需求是设置描边色,调整为以下代码(记得加描边宽度,否则可能看不到效果):

.voted svg path {
    color: green;
    stroke: currentColor;
    stroke-width: 2;
}

同时确保SVG的path没有写死stroke值,或者给path添加stroke="currentColor"。


内容的提问来源于stack exchange,提问作者Max Pattern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:40:54