今日已更新 133 条资讯 | 累计 37382 条内容
关于我们

The SVG Color Cascade Nobody Explains (fill, stroke, currentColor, and why img src breaks it)

Usman Bashir 2026年08月08日 01:53 9 次阅读 来源:Dev.to

Change an SVG's color by editing fill and stroke , either as attributes or through CSS. Simple in theory. In practice there are three places a color can be declared in the same file, they follow the normal CSS cascade, and if you don't know that, "I changed the fill and nothing happened" turns into a twenty-minute debugging session. Here's the part of SVG color handling that usually doesn't get spelled out. fill and stroke are separate properties Every shape has an inside ( fill ) and an outline ( stroke ), set independently: <circle cx= "50" cy= "50" r= "40" fill= "#3366ff" stroke= "#000" stroke-width= "2" /> Unset fill defaults to black. Unset stroke defaults to none. If an icon is pure fill with no stroke at all (most converted icon-font SVGs are), editing stroke-width is never going to do anything visible, and that's usually the first dead end people hit. The cascade is the actual bug source A color can come from three places, and they don't have equal priority: A presentation attribute: <path fill="red" /> An inline style attribute: <path style="fill: red;" /> A <style> block or external stylesheet: path { fill: red; } Normal CSS specificity applies: style attribute beats stylesheet, stylesheet beats presentation attribute. Edit the fill="red" attribute directly, and if a <style> block elsewhere in the same file also targets that path, your edit is overridden and nothing changes on screen. No error, no warning, it just loses. If a color edit isn't sticking, grep the file for <style before assuming your tool, or your edit, is broken. This one thing accounts for most "the SVG editor is buggy" reports that are actually the cascade working exactly as designed. currentColor: SVG's inheritance trick Set fill="currentColor" and the shape stops carrying its own color and instead inherits whatever color is set to on an ancestor element, the same mechanism that makes text inherit color: <path fill= "currentColor" d= "..." /> .icon { color : #ff0000 ; } <span class= "icon

本文内容来源于互联网,版权归原作者所有
查看原文