How can I change the color of an 'svg' element?
Categories:
Mastering SVG Color: A Comprehensive Guide to Styling SVG Elements

Learn various techniques to change the color of SVG elements using CSS, inline styles, and JavaScript for dynamic control.
Scalable Vector Graphics (SVG) are a powerful tool for web development, offering resolution independence and small file sizes. Unlike raster images, SVGs are XML-based, meaning their properties, including color, can be manipulated directly through CSS, inline styles, or JavaScript. This article explores the most common and effective methods for changing the color of SVG elements, providing practical examples and best practices.
Understanding SVG Color Properties
Before diving into specific methods, it's crucial to understand the primary SVG properties that control color. The two most common are fill
and stroke
. fill
defines the color inside the shape, while stroke
defines the color of the outline. Both can accept any valid CSS color value (e.g., hex codes, RGB, RGBA, HSL, named colors).
flowchart TD A[SVG Element] --> B{Has `fill` attribute?} B -- Yes --> C[Applies fill color] B -- No --> D[Default: black] A --> E{Has `stroke` attribute?} E -- Yes --> F[Applies stroke color] E -- No --> G[Default: none]
Decision flow for SVG fill and stroke properties.
Method 1: Using Inline Styles
The most direct way to apply color to an SVG element is through inline styles. This involves adding fill
and stroke
attributes directly to the SVG tags. While straightforward, this method can become cumbersome for complex SVGs or when you need to change colors dynamically across multiple elements.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="#FF5733" stroke="#C70039" stroke-width="5" />
<rect x="10" y="10" width="30" height="30" fill="blue" />
</svg>
Applying inline fill
and stroke
attributes to SVG shapes.
Method 2: Styling with External CSS
Using external or internal CSS is generally the preferred method for styling SVGs. It promotes separation of concerns, makes your styles reusable, and allows for easier maintenance. You can target SVG elements by their tag name, class, or ID, just like any other HTML element.
/* styles.css */
.my-svg-icon {
fill: #33FF57;
stroke: #00C739;
stroke-width: 2px;
}
.my-svg-icon:hover {
fill: #5733FF;
}
/* In your HTML */
<svg width="100" height="100" class="my-svg-icon">
<path d="M50 10 L90 90 L10 90 Z" />
</svg>
Styling an SVG path using a CSS class.
<img>
tag. External SVGs referenced via <img>
or background-image
cannot be styled with CSS from the parent document due to security restrictions (Same-Origin Policy).Method 3: Dynamic Coloring with JavaScript
For interactive or dynamic color changes, JavaScript is your go-to solution. You can manipulate SVG element styles directly using the DOM API, allowing for complex interactions, user-driven color changes, or integration with application state.
document.addEventListener('DOMContentLoaded', () => {
const svgElement = document.getElementById('dynamic-svg');
const circle = svgElement.querySelector('circle');
// Change fill color on click
circle.addEventListener('click', () => {
const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
circle.style.fill = randomColor;
console.log(`Circle color changed to: ${randomColor}`);
});
// Initial styling
circle.style.fill = 'purple';
circle.style.stroke = 'black';
circle.style.strokeWidth = '3px';
});
/* In your HTML */
<svg id="dynamic-svg" width="100" height="100">
<circle cx="50" cy="50" r="40" />
</svg>
Changing SVG fill color dynamically with JavaScript.
Best Practices for SVG Coloring
To ensure maintainability, accessibility, and performance, consider these best practices when coloring your SVGs:
1. Prefer CSS for Static Styling
For colors that don't change based on user interaction or application state, use external CSS. This keeps your styles organized and easily modifiable.
2. Use Classes for Reusability
Apply CSS classes to your SVG elements to group similar styles and make them reusable across your project.
3. Optimize SVG Structure
Before embedding, optimize your SVG files using tools like SVGO to remove unnecessary attributes and reduce file size. This can also make them easier to style.
4. Consider currentColor
For simple icons that should inherit the text color of their parent, use fill="currentColor"
or stroke="currentColor"
. This allows the SVG to automatically match the surrounding text color defined by CSS.
5. Test Accessibility
Ensure sufficient color contrast for accessibility. Tools like WebAIM's Contrast Checker can help verify your color choices.