Modify SVG Styles in C# – Fill, CSS, and Inline Styles

This article shows how to change SVG styles programmatically in C#: update fill and stroke, rewrite inline style attributes, remove blocking styles from design-tool exports, and add global CSS rules before rendering or converting SVG files.

You will learn how to:

Why SVG Style Changes May Not Apply

In real-world workflows, SVG files are rarely authored for programmatic processing. They are typically produced by design tools, third-party services, or user uploads and contain a mix of styling mechanisms:

These mechanisms do not have equal priority. The normal priority order is inline styles → CSS rules → presentation attributes. If this is not taken into account, programmatic style changes may appear to not work even though the code executes correctly. Before changing anything, it is crucial to understand where styles come from and which ones take precedence. If you’re not familiar with SVG styling models, see SVG CSS vs Inline Styles vs Presentation Attributes in C#.

This guide focuses on DOM-level style modification with Aspose.SVG for .NET. For a broader troubleshooting guide, including font and conversion issues, see Common SVG Styling and Font Issues in C#.

Choose a Style Modification Strategy

GoalRecommended approachUse when
Change one property and preserve the restRewrite selected declarations inside the style attributeImported SVGs contain important inline styles
Remove style conflicts from generated SVGRemove inline style attributesYou will replace them with CSS rules or presentation attributes
Apply one visual rule to many elementsInsert a global <style> elementYou need consistent styling for text, shapes, or groups
Make simple DOM updatesSet presentation attributes like fill or strokeThe SVG is generated or controlled by your code

Find Inline Styles That Override Your Changes

If an SVG element has an inline style attribute, changing CSS rules or presentation attributes will not affect rendering. Therefore, every style change process should begin by checking inline styles. Using Aspose, you can inspect your document and identify where inline styles are used to inform your future strategy for changing and applying styles.

Example: Detect Inline Style Attributes in an SVG Document

1using Aspose.Svg.Dom;
2using System.IO;
 1// Find SVG elements that use inline style attributes in C#
 2
 3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
 4
 5// Select all elements that have inline style attributes
 6var styledNodes = document.QuerySelectorAll("[style]");
 7
 8Console.WriteLine($"Found {styledNodes.Length} element(s) with inline styles:\n");
 9
10foreach (var node in styledNodes)
11{
12    var element = (Element)node;
13
14    // Get and display the style attribute value
15    string styleValue = element.GetAttribute("style");
16    Console.WriteLine($"Element: <{element.TagName}>");
17    Console.WriteLine($"Style: {styleValue}\n");
18}

After running the example, you will gain information about all inline style attributes and decide how to modify a particular element’s style to avoid conflicts.

1    Element: <line>
2    Style: stroke:grey; stroke-width:5
3
4    Element: <polygon>
5    Style: fill:orange; stroke:purple; stroke-width:1; fill-opacity:1
6
7    Element: <ellipse>
8    Style: fill:orangered

Why this matters

  • Inline style attributes override all other styling mechanisms.
  • Design tools like Illustrator and Figma typically export SVGs with inline style attributes.
  • Ignoring this step leads to “why didn’t my change apply?” bugs.

Update Specific Inline CSS Properties

When to Preserve Inline Styles

Avoid removing all inline styles when:

Instead of deleting inline style attributes blindly, you can read, modify, and rewrite them. To modify inline styles safely, you must:

This approach ensures predictable rendering by eliminating style conflicts and centralizing visual properties.

Example: Change Fill by Rewriting Inline Styles

The following C# example shows how to change SVG fill safely. It finds all elements with inline styles using QuerySelectorAll, removes the fill property from their style attribute, and sets a consistent fill color using the fill presentation attribute instead.

1using Aspose.Svg.Dom;
2using System.IO;
3using System;
4using System.Collections.Generic;
 1// Remove specific inline CSS properties and replace them with SVG attributes in C#
 2
 3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
 4
 5// Select elements that contain inline styles
 6var nodes = document.QuerySelectorAll("[style]");
 7foreach (var node in nodes)
 8{
 9    var element = (Element)node;
10    // Read inline style as plain text
11    var style = element.GetAttribute("style");
12    if (string.IsNullOrEmpty(style))
13        continue;
14    // Remove only fill-related declarations
15    var cleanedStyle = RemoveStyleProperty(style, "fill");
16    if (string.IsNullOrWhiteSpace(cleanedStyle))
17    {
18        // Remove empty style attribute
19        element.RemoveAttribute("style");
20    }
21    else
22    {
23        element.SetAttribute("style", cleanedStyle);
24    }
25    // Apply deterministic presentation attribute
26    element.SetAttribute("fill", "#FF7A00");
27}
28// Save the modified SVG document
29document.Save(Path.Combine(OutputDir, "style-normalized.svg"));
30
31// --- Helper method ---
32static string RemoveStyleProperty(string style, string property)
33{
34    var declarations = style.Split(';');
35    var result = new List<string>();
36    foreach (var decl in declarations)
37    {
38        if (!decl.TrimStart().StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
39        {
40            result.Add(decl.Trim());
41        }
42    }
43    return string.Join("; ", result);
44}

Remove Inline Style Attributes

Complete removal of inline styles is appropriate in specific scenarios, but should be used with caution.

When to Remove All Inline Styles

However, complete style removal carries significant risks. Elements may revert to their default appearance with black fill and default fonts; layouts can break due to lost positioning, transforms, or opacity settings; and these changes are irreversible. Therefore, always inspect the document structure and ensure alternative styling is in place before proceeding.

Best practice: Always inspect the document structure before bulk style removal, and ensure alternative styling is in place.

Example: Remove All Inline style Attributes from SVG Elements

The following C# example shows how to remove all inline style attributes in SVG document:

1using Aspose.Svg.Dom;
2using System.IO;
 1// Remove all inline style attributes from SVG elements to prevent CSS conflicts in C#
 2
 3// Load an existing SVG document
 4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
 5
 6// Select all elements that have inline style attributes
 7var nodes = document.QuerySelectorAll("[style]");
 8
 9// Iterate through all styled elements
10foreach (var node in nodes)
11{
12    // Cast node to Element and remove the style attribute
13    if (node is Element element)
14    {
15        element.RemoveAttribute("style");
16    }
17}
18
19// Save the modified SVG document without inline styles
20document.Save(Path.Combine(OutputDir, "inline-styles-removed.svg"));

This creates a clean baseline for CSS rules or presentation attributes.

Replace Inline Styles with a Global <style> Element

This example demonstrates a common SVG normalization workflow: removing scattered inline styles and replacing them with centralized CSS rules. This approach improves maintainability, reduces file size, and ensures consistent styling across all text elements.

Example: Apply Global CSS Rules After Normalization

1using Aspose.Svg.Dom.Svg;
2using System.IO;
 1// Apply global CSS styles to SVG text after removing conflicting inline styles in C#
 2
 3// Load SVG document
 4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg")))
 5{
 6    // Select all text-related elements
 7    var textNodes = document.QuerySelectorAll("text, tspan");
 8
 9    // Remove inline style attributes
10    for (int i = 0; i < textNodes.Length; i++)
11    {
12        Element element = textNodes[i] as Element;
13        if (element != null && element.HasAttribute("style"))
14        {
15            element.RemoveAttribute("style");
16        }
17    }
18
19    // Create global <style> element
20    SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
21    style.SetAttribute("type", "text/css");
22    style.TextContent =
23        "text { " +
24        "font-family: 'DejaVu Sans', sans-serif; " +
25        "font-size: 16px; " +
26        "fill: #2c3e50; " +
27        "}";
28
29    // Insert style at the top of SVG
30    SVGSVGElement root = document.RootElement;
31    root.InsertBefore(style, root.FirstChild);
32
33    // Save result
34    document.Save(Path.Combine(OutputDir, "styled-text.svg"));
35}

The example uses QuerySelectorAll to target all text-related elements, removes their inline styles, and inserts a global style rule at the beginning of the document using InsertBefore.

Choose the appropriate strategy based on your workflow:

  • Rewrite selected inline declarations if you need to preserve most existing styling.
  • Remove inline style attributes when cleaning uncontrolled or generated SVG files.
  • Add a global <style> element when enforcing consistent, centralized styling.

Final Workflow Summary

A reliable SVG style modification pipeline in C# follows this order:

  1. Inspect inline styles
  2. Normalize or remove blocking declarations
  3. Apply presentation attributes or CSS rules
  4. Save, render, or convert the SVG with predictable results

Skipping these steps often leads to style changes that execute successfully in code but do not affect the rendered SVG.