Introduction
Scalable Vector Graphics (SVG) are widely used for their scalability and versatility, especially in web design. A common requirement is to dynamically change the fill color of SVG paths using CSS. This tutorial explains how to achieve this by leveraging various CSS techniques.
Understanding SVG Basics
An SVG file contains vector images defined by XML-based markup language. Key elements include <svg>
, which defines the container, and <path>
, which specifies shapes within the SVG. The fill
attribute in a path element determines its color.
Changing Fill Color with External CSS
To change an SVG path’s fill color using external CSS, you can target the <path>
element directly if it is not nested deeply or has unique identifiers. Here’s how:
Example 1: Basic CSS Targeting
<svg height="32" width="32">
<path d="M10 10 H 90 V 90 H 10 Z" fill="#333333"/>
</svg>
/* Change the path color to blue */
path {
fill: blue;
}
This approach works if there are no inline styles with !important
or higher specificity that override this CSS.
Example 2: Using Class Selectors
If multiple paths need different colors, use class selectors:
<svg height="32" width="32">
<path class="circle-path" d="M10 10 H 90 V 90 H 10 Z"/>
<path class="square-path" d="M50 10 H 70 V 30 H 50 Z"/>
</svg>
.circle-path {
fill: green;
}
.square-path {
fill: yellow;
}
Advanced Techniques
Hover Effects
To change the color on hover, use pseudo-classes:
<svg height="32" width="32">
<path d="M10 10 H 90 V 90 H 10 Z"/>
</svg>
path:hover {
fill: red;
}
CSS Variables for Dynamic Colors
CSS variables offer a powerful way to manage colors dynamically:
<svg height="32" width="32">
<path style="--svgcolor: #333;" d="M10 10 H 90 V 90 H 10 Z"/>
</svg>
path {
fill: var(--svgcolor);
}
/* Change color on hover */
span:hover path {
--svgcolor: aquamarine;
}
Using CSS for SVG Imported as Image
If an SVG is embedded via <img>
or <object>
, styling directly with CSS is not possible. However, if the SVG content is inlined within HTML:
<object data="image.svg" type="image/svg+xml">
<!-- Fallback content -->
</object>
You can manipulate it by converting it into an inline format and applying styles.
Best Practices
- Avoid Inline Styles: Use classes or IDs to manage styles externally for better scalability.
- Use Specific Selectors: Ensure your selectors are specific enough to override any default or inline styling.
- Leverage CSS Variables: They make it easy to maintain and dynamically change colors across multiple SVGs.
Conclusion
Changing the fill color of an SVG path with CSS is a straightforward task when you understand how CSS interacts with SVG elements. Whether through basic targeting, pseudo-classes for hover effects, or dynamic styling with CSS variables, these techniques allow for versatile and responsive design.