Replacing Colors in SVG
A practical guide to replacing colors in SVG files, including fill and stroke attributes, CSS styles, currentColor, inline SVG, external files, and automated color replacement.
Replacing colors in an SVG is one of the most common tasks when working with icons, illustrations, logos, diagrams, and interface graphics. Because SVG is text-based XML, colors can often be changed directly in the markup instead of editing the original image in a graphics application.
The important part is understanding where the color is defined. An SVG may use fill and stroke attributes, inline style declarations, CSS classes, external stylesheets, presentation attributes, gradients, masks, or the special currentColor value. Replacing a color therefore is not always as simple as finding one HEX value and changing it.
This guide explains the main ways SVG colors are defined and how to replace them safely without accidentally changing unrelated parts of the graphic.
Where SVG Colors Are Defined
The most common SVG color properties are fill and stroke. The fill controls the inside of a shape, while stroke controls its outline. These can appear directly as attributes on SVG elements or be supplied through CSS.
<svg viewBox="0 0 100 100">
<circle
cx="50"
cy="50"
r="30"
fill="#2563eb"
stroke="#1e3a8a"
stroke-width="4"
/>
</svg>In this example, the circle has a blue fill and a darker blue stroke. Replacing either value changes a different visual part of the shape.
Replacing a HEX Color
The simplest case is an SVG that contains explicit HEX colors. A color such as #2563eb can be replaced directly with another color.
<path
d="M10 10h80v80H10z"
fill="#2563eb"
/>For example, changing #2563eb to #7c3aed turns the shape from blue to purple.
<path
d="M10 10h80v80H10z"
fill="#7c3aed"
/>Replacing Multiple Occurrences
A single SVG may use the same color many times. For example, several paths can share the same fill value.
<svg viewBox="0 0 200 100">
<circle cx="40" cy="50" r="25" fill="#2563eb" />
<rect x="75" y="25" width="50" height="50" fill="#2563eb" />
<path d="M145 25h30v50h-30z" fill="#2563eb" />
</svg>Replacing every occurrence of #2563eb with another value changes all three shapes consistently. This is useful when an SVG uses a small palette and the same color represents the same design token throughout the illustration.
However, global replacement should be used carefully. The same hexadecimal value may have been used for different purposes. A color might represent both an icon's primary fill and an unrelated decorative element, even though the numeric color value is identical.
SVG Fill Colors
The fill property determines the interior paint of most SVG shapes. It can be specified directly on an element.
<rect
x="10"
y="10"
width="80"
height="80"
fill="#ef4444"
/>Changing the fill changes the interior of the rectangle without affecting its stroke.
<rect
x="10"
y="10"
width="80"
height="80"
fill="#22c55e"
/>If an SVG does not have an explicit fill on an element, the element may inherit the fill value from a parent element or CSS rule. This is important when trying to replace colors programmatically.
SVG Stroke Colors
The stroke property controls the outline of an SVG shape. It is commonly combined with stroke-width.
<circle
cx="50"
cy="50"
r="30"
fill="none"
stroke="#111827"
stroke-width="5"
/>If you only replace fill values, the stroke remains unchanged. When recoloring an SVG, check both fill and stroke if the illustration uses outlines.
Replacing Colors Defined with CSS
SVG colors are not always written directly on each element. They can be defined in a style block or an external stylesheet.
<svg viewBox="0 0 100 100">
<style>
.primary {
fill: #2563eb;
}
</style>
<circle
class="primary"
cx="50"
cy="50"
r="30"
/>
</svg>In this case, changing the fill attribute on the circle would not be the right approach because the color comes from the .primary CSS rule.
.primary {
fill: #7c3aed;
}When an SVG uses classes extensively, changing the CSS definition can be more maintainable than adding individual fill attributes to every element.
Inline Style Attributes
Another common format is an inline style attribute.
<path
d="M10 10h80v80H10z"
style="fill:#2563eb;stroke:#111827;stroke-width:3"
/>Here the colors are part of the style string rather than standalone fill and stroke attributes. A color replacement process needs to account for this syntax as well.
Presentation Attributes vs CSS
SVG supports presentation attributes such as fill and stroke, but those properties can also be controlled through CSS. This means the visible color may not always be obvious from a quick inspection of one element.
<svg viewBox="0 0 100 100">
<style>
.shape {
fill: #2563eb;
}
</style>
<rect
class="shape"
x="10"
y="10"
width="80"
height="80"
fill="#ef4444"
/>
</svg>When multiple declarations target the same property, CSS cascading and specificity determine which declaration wins. Simply replacing the first color you find may therefore have no visible effect.
Using currentColor
The currentColor keyword is particularly useful for SVG icons. It tells the browser to use the element's current CSS color value.
<svg
class="icon"
viewBox="0 0 24 24"
width="24"
height="24"
>
<path
d="M5 12h14M12 5v14"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
</svg>.icon {
color: #2563eb;
}
.icon:hover {
color: #7c3aed;
}This approach avoids hardcoding the same color inside the SVG. The icon inherits its color from CSS, making themes and state changes easier to implement.
Replacing Black SVG Colors
Many downloaded SVG icons use black as their primary color. The black may appear as #000, #000000, rgb(0 0 0), or simply black.
<svg viewBox="0 0 100 100">
<path d="M10 10h80v80H10z" fill="#000000" />
<circle cx="50" cy="50" r="20" fill="black" />
</svg>These are different textual representations of black. A simple string replacement for #000000 will not replace black or rgb(0 0 0). A robust color replacement process should understand the different color syntaxes that may occur in an SVG.
Replacing RGB and RGBA Colors
SVG colors can also be written using rgb() and rgba() syntax.
<circle
cx="50"
cy="50"
r="30"
fill="rgb(37, 99, 235)"
/>Modern CSS color syntax can also use space-separated RGB values and an optional alpha component.
<circle
cx="50"
cy="50"
r="30"
fill="rgb(37 99 235 / 80%)"
/>When replacing colors automatically, supporting only HEX values can miss colors written in other valid formats.
Replacing HSL Colors
SVG can also use HSL and related CSS color functions.
<path
d="M10 10h80v80H10z"
fill="hsl(220 90% 55%)"
/>HSL is particularly useful when colors need to be adjusted by hue, saturation, or lightness. However, if the goal is to replace one exact color throughout a file, converting all colors into a consistent representation can make processing easier.
Replacing Named Colors
SVG also accepts CSS color keywords such as red, blue, white, black, transparent, and many others.
<rect
x="10"
y="10"
width="80"
height="80"
fill="royalblue"
/>Named colors are valid, but they can make automated color replacement less predictable because there are many possible textual representations for the same or similar colors.
Replacing Colors in Gradients
Gradients require special attention because their colors are usually stored in stop elements rather than directly on the shape.
<svg viewBox="0 0 200 100">
<defs>
<linearGradient id="gradient">
<stop offset="0%" stop-color="#2563eb" />
<stop offset="100%" stop-color="#7c3aed" />
</linearGradient>
</defs>
<rect
x="10"
y="10"
width="180"
height="80"
fill="url(#gradient)"
/>
</svg>The rectangle itself does not contain the actual gradient colors. It references the gradient with url(#gradient), while the colors are defined by stop-color on the individual stops.
If an automated tool only searches for fill and stroke values, it may completely miss colors inside gradients.
Replacing Colors in Patterns
SVG patterns can also contain shapes with their own colors.
<svg viewBox="0 0 100 100">
<defs>
<pattern
id="pattern"
width="20"
height="20"
patternUnits="userSpaceOnUse"
>
<rect width="20" height="20" fill="#2563eb" />
<circle cx="10" cy="10" r="4" fill="#ffffff" />
</pattern>
</defs>
<rect
width="100"
height="100"
fill="url(#pattern)"
/>
</svg>Changing the visible color of a pattern therefore requires editing the colors of the elements inside the pattern definition.
Replacing Colors in Masks and Filters
Masks and filters can make color replacement more complicated. A graphic may appear to have a particular color even though that color is produced through several SVG elements, opacity values, blending, or filter effects.
Before replacing a color in a complex SVG, inspect the definitions inside the defs element. Gradients, masks, clip paths, filters, and reusable symbols may contain the actual visual source of a color.
Replacing Colors in Inline SVG
Inline SVG is embedded directly into an HTML document. Because its elements are part of the page DOM, CSS can target them directly.
<button class="icon-button">
<svg
class="icon"
viewBox="0 0 24 24"
aria-hidden="true"
>
<path
class="icon-shape"
d="M5 12h14"
stroke="#2563eb"
stroke-width="2"
/>
</svg>
</button>.icon-button .icon-shape {
stroke: #7c3aed;
}This makes inline SVG particularly convenient when colors need to change according to themes, hover states, application state, or user preferences.
Replacing Colors in External SVG Files
An external SVG can be referenced with an img element or another embedding method.
<img
src="/icons/search.svg"
alt="Search"
/>The parent document generally cannot use ordinary CSS selectors to reach the internal elements of an SVG loaded through img. If you need to dynamically recolor individual paths from the page, converting the SVG to inline markup is often a more practical approach.
Replacing Colors in SVG Sprites
SVG sprites commonly contain multiple symbols that are reused with the use element. Color handling depends on how the symbols are authored, but currentColor is often useful for creating reusable icons.
<symbol id="search-icon" viewBox="0 0 24 24">
<path
d="M10 4a6 6 0 1 0 0 12a6 6 0 0 0 0-12z"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
</symbol>A sprite designed around currentColor can be recolored at the point where the icon is used, avoiding separate copies of the same SVG for different colors.
Replacing Colors with JavaScript
When an SVG is inline, JavaScript can access its elements through the DOM and change their attributes or styles.
const shapes = document.querySelectorAll(".icon-shape");
shapes.forEach((shape) => {
shape.setAttribute("fill", "#7c3aed");
});This approach is useful when the color depends on runtime state. However, if the change is purely presentational, CSS is usually simpler and avoids unnecessary JavaScript.
Replacing SVG Colors in React
In React, SVG colors can be controlled through props, CSS classes, inline styles, or CSS variables. For reusable components, passing a color as a prop can be convenient.
type IconProps = {
color?: string;
};
export function Icon({
color = "#2563eb",
}: IconProps) {
return (
<svg
viewBox="0 0 24 24"
width="24"
height="24"
aria-hidden="true"
>
<path
d="M5 12h14"
stroke={color}
strokeWidth="2"
fill="none"
/>
</svg>
);
}For a larger design system, currentColor or CSS custom properties can be even more flexible because the component does not need to know every possible theme color.
Using CSS Variables for SVG Colors
CSS custom properties are useful when the same SVG needs to support different themes or states.
.icon {
--icon-color: #2563eb;
color: var(--icon-color);
}
.icon.is-active {
--icon-color: #7c3aed;
}<svg
class="icon"
viewBox="0 0 24 24"
>
<path
d="M5 12h14"
stroke="currentColor"
stroke-width="2"
/>
</svg>This separates the SVG structure from the color theme and makes global theme changes easier to maintain.
Replacing Colors Without Changing Transparency
A color can be combined with opacity. When recoloring an SVG, make sure you understand whether transparency comes from the color itself or from a separate opacity property.
<path
d="M10 10h80v80H10z"
fill="#2563eb"
fill-opacity="0.5"
/>Replacing the fill with another color does not automatically remove fill-opacity. The new color will still be rendered with the existing transparency.
Replacing Colors While Preserving Contrast
A replacement color that looks good in isolation may not provide enough contrast against the background. This is particularly important for icons, text-like SVG elements, buttons, and other interface graphics.
When changing a color used for meaningful interface content, check the resulting foreground and background combination rather than choosing the new color only by appearance.
A Simple Manual Replacement Workflow
For a small SVG, manual editing is often enough. Open the SVG as text, search for the existing color, determine where it is used, replace it, and preview the result.
If the color appears in many places, replace all occurrences only after confirming that those occurrences should change together. For more complex SVGs, inspect styles, gradients, patterns, and defs before making a global replacement.
Automating Color Replacement
For repeated processing, color replacement can be automated. At the simplest level, a string replacement can change an exact color value.
const svg = '<path fill="#2563eb" d="M10 10h80v80H10z" />';
const updatedSvg = svg.replaceAll(
"#2563eb",
"#7c3aed"
);
console.log(updatedSvg);This is sufficient when the SVG format is controlled and the exact textual representation is known. It becomes less reliable when the file may contain uppercase HEX values, shorthand HEX, rgb(), hsl(), named colors, CSS variables, or colors defined through styles and gradients.
Why Simple String Replacement Can Fail
SVG is structured XML, not merely a collection of color strings. A production-quality recoloring system may need to parse the document and inspect attributes and styles rather than blindly replacing text.
| Color source | Simple text replacement | What to inspect |
|---|---|---|
| fill attribute | Usually works | fill value |
| stroke attribute | Usually works | stroke value |
| style attribute | May work | CSS declarations |
| style block | May work | CSS rules |
| Gradient | Only if stop color is found | stop-color and stop-opacity |
| Pattern | Only if nested colors are found | Elements inside pattern |
| currentColor | Not applicable | Parent CSS color |
| CSS variable | Not applicable | Variable declaration |
Normalizing SVG Colors
If SVG files come from different sources, the same visual color may be represented in different formats. One file might use #2563eb, another rgb(37 99 235), and another an equivalent HSL value.
A more advanced recoloring workflow can parse color values, convert them into a common representation, compare them, and then write the desired replacement format back into the SVG.
This is more reliable than comparing raw strings, especially when files originate from different design tools.
Preserving SVG Structure
Color replacement should ideally change only the required values. Avoid rewriting the entire SVG unnecessarily because unrelated formatting, metadata, namespaces, IDs, or reusable definitions may be changed by an aggressive transformation process.
If the SVG is part of a build pipeline, verify that the resulting file still renders correctly and that references such as url(#gradient), clip-path, masks, and symbol IDs remain intact.
Replacing Colors in Multi-Color Illustrations
Multi-color illustrations often use several colors for different semantic roles. Instead of replacing every color with one value, it can be better to map the original palette to a new palette.
| Original role | Example | Replacement role |
|---|---|---|
| Primary | #2563eb | Brand primary |
| Secondary | #7c3aed | Brand secondary |
| Dark detail | #111827 | Dark neutral |
| Light background | #f8fafc | Light surface |
This approach is especially useful for rebranding illustrations or adapting a downloaded SVG to a design system.
SVG Color Replacement for Dark Mode
Dark mode is a common reason to recolor SVGs. A graphic that works on a white background may use dark fills that become difficult to see on a dark background.
.icon {
color: #111827;
}
@media (prefers-color-scheme: dark) {
.icon {
color: #f8fafc;
}
}Using currentColor or CSS variables makes this kind of theme adaptation much easier than maintaining separate SVG files for light and dark interfaces.
Replacing Colors in Logos
Logos often contain a small number of fixed colors, making SVG a convenient format for creating brand variants. A monochrome version, dark version, light version, and accent version can often be generated from the same source SVG.
Before modifying a logo, check whether the source artwork uses gradients, transparency, masks, or multiple paths that happen to share the same color. A global replacement may not produce the intended brand variant.
Common SVG Color Replacement Mistakes
- Replacing only fill while forgetting that important colors may be defined with stroke.
- Searching only for HEX values and missing rgb(), hsl(), named colors, or CSS variables.
- Changing every occurrence of a color without checking whether all uses should change together.
- Ignoring colors inside gradients, patterns, masks, or reusable definitions.
- Trying to style an external SVG loaded with img from the parent document.
- Removing currentColor and replacing it with a hardcoded value when the icon is intended to inherit its color.
- Changing a color without checking contrast against the actual background.
- Rewriting or optimizing the whole SVG when only a few color values needed to change.
- Assuming that two visually similar colors are identical textual values.
- Using JavaScript for a purely presentational color change that CSS could handle more simply.
A Practical SVG Recoloring Workflow
First inspect the SVG and identify how its colors are defined. Look for fill, stroke, style attributes, CSS rules, currentColor, gradients, patterns, and CSS variables. Then decide whether the change should affect one element, one color globally, or an entire palette.
For a simple controlled SVG, direct editing or exact string replacement may be enough. For reusable interface icons, currentColor or CSS variables are usually more maintainable. For complex or user-supplied SVG files, parsing the SVG structure is safer than relying on unrestricted text replacement.
After the replacement, render the SVG and verify that every intended element changed while unrelated elements remained intact. If the SVG is used in an interface, also check contrast, dark mode behavior, accessibility, and different backgrounds.
Frequently Asked Questions
How do I change the color of an SVG?
Find the SVG's fill or stroke value and replace it with the desired color. If the SVG uses CSS, gradients, currentColor, or other mechanisms, the color may need to be changed in those definitions instead.
Can I replace all colors in an SVG at once?
Yes, if you know which colors should change together. For a simple SVG, replacing all occurrences of an exact color value can work. Complex SVGs require more care because colors can appear in CSS, gradients, patterns, and other definitions.
Why does changing fill not change my SVG?
The visible color may come from stroke, a CSS rule, an inline style, currentColor, a gradient, or another definition. Inspect the SVG's styles and referenced definitions to find the actual source of the color.
Can I change the color of an SVG with CSS?
Yes, especially for inline SVG. CSS can target SVG elements and their fill and stroke properties. Using currentColor is also a convenient way to make an SVG inherit its color from surrounding CSS.
Can I recolor an SVG loaded with img?
The parent document cannot normally target the internal SVG elements of an SVG loaded through img with ordinary CSS selectors. For direct DOM styling, inline SVG or another embedding approach is usually more suitable.
How do I recolor an SVG without changing its transparency?
Replace the color value while leaving properties such as fill-opacity, stroke-opacity, opacity, masks, and filters unchanged. The resulting SVG should then preserve the existing transparency behavior.
What is the best way to make an SVG support multiple colors?
For reusable interface graphics, currentColor or CSS custom properties are often the most flexible approaches. They allow the same SVG markup to work with different themes and states without creating separate files.
Helpful SVG Color Tools
An SVG Color Replacer is useful when you need to substitute one or more colors in an SVG without editing every occurrence manually. An SVG Formatter can make the markup easier to inspect, while an SVG Viewer helps verify the rendered result after recoloring. A HEX Color Picker is useful when selecting replacement colors, and a Color Contrast Checker can help verify that the new color remains sufficiently distinguishable from its background.
Conclusion
Replacing colors in SVG can be as simple as changing a fill or stroke value, but real-world SVG files often use CSS, currentColor, gradients, patterns, variables, and other mechanisms. Understanding where a color comes from is therefore more important than simply searching for a HEX value.
For small and controlled SVG files, manual editing or exact replacement is often sufficient. For reusable UI graphics, currentColor and CSS variables provide a more maintainable approach. For automated processing of complex SVG files, parsing the document and handling different color representations is safer than unrestricted string replacement.
After recoloring an SVG, always preview the result and check that the intended elements changed, transparency was preserved, and the new colors work against their actual backgrounds. A careful recoloring workflow keeps the SVG reusable while avoiding unnecessary changes to its structure.