Change SVG Background Color – C# Examples
SVG background color is critical to providing visual clarity and contrast, improving the content’s visibility and aesthetics. It is vital in maintaining design consistency, improving accessibility by providing readable text, and defining boundaries in multi-layered compositions. You can change the background color of an SVG either by modifying the SVG directly or by applying styles using CSS or JavaScript.
Aspose.SVG for .NET API lets you edit an SVG document and make changes to its content.
In this article, you will learn how to apply background color to SVG files using Aspose.SVG for .NET and how to work with background color for SVG images inside HTML documents using Aspose.HTML C# library.
Modify SVG Directly
To set the background color of an SVG image, you should insert a new SVG element, such as a rectangle or circle, as the first child element in the SVG document. This method takes a rule about the order of SVG elements – elements that appear later in the SVG code appear on top of those that appear earlier. By placing a rectangle or circle at the beginning of the SVG, you effectively create a background layer that sits underneath all other graphic elements.
Add Background to SVG
The most common method for setting the background color in SVG is to create a <rect>
element that covers the entire SVG canvas. This approach ensures that the background is part of the SVG content itself. The following code snippet illustrates how to add background to SVG – create a new rectangle element in SVG that will serve as a background. To do this, the rectangle is given the width="100%"
, height="100%"
and fill="#ebf3f6"
attributes, and is positioned so that it appears behind all other SVG content:
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Set SVG Namespace Url
6 string SvgNamespace = "http://www.w3.org/2000/svg";
7
8 string documentPath = Path.Combine(DataDir, "tree.svg");
9
10 // Load an SVG document from the file
11 var document = new SVGDocument(documentPath);
12
13 // Get root <svg> element of the document
14 var svgElement = document.RootElement;
15
16 // Create a rectangle element and set the "width", "height" and "fill" attributes
17 var rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
18 rectElement.X.BaseVal.Value = 3;
19 rectElement.Y.BaseVal.Value = 3;
20 rectElement.SetAttribute("width", "100%");
21 rectElement.SetAttribute("height", "100%");
22 rectElement.SetAttribute("fill", "#ebf3f6");
23
24 // Add the rectangle element as the first child to <svg> element
25 svgElement.InsertBefore(rectElement, svgElement.FirstChild);
26
27 // Save the SVG document
28 document.Save(Path.Combine(OutputDir, "add-background-color.svg"));
Change SVG Background Color
If your SVG document has an element that serves as a background, such as a rectangle as in the previous example, changing the background color involves several steps:
- Open a source SVG file.
- Get the root
<svg>
element of the document. - Get the first rectangle element (or another SVG element that serves as background) to change color.
- Set a new fill attribute value for the
<rect>
element. - Save the edited SVG document.
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Load an SVG document from a file
6 var document = new SVGDocument(Path.Combine(DataDir, "add-background-color.svg"));
7
8 // Get root svg element of the document
9 var svgElement = document.RootElement;
10
11 // Get the first <rect> element to change color
12 var rectElement = svgElement.QuerySelector("rect") as SVGRectElement;
13
14 // Set a new "fill" attribute value for the <rect> element
15 rectElement.SetAttribute("fill", "#fef4fd");
16
17 // Save the SVG document
18 document.Save(Path.Combine(OutputDir, "change-background-color.svg"));
Note: This way (<rect>
method) is the most consistent across browsers and ensures that the background color is part of the SVG, even when the SVG is exported or used in different contexts.
The following figure shows the original SVG image (a), the image with the background added (b), and the image in which the SVG background color has been changed (c):
Change Background Color Using CSS
Changing SVG background color using CSS is a common task that enhances the visual presentation of SVG images within web pages. While SVG elements don’t support a native background-color
property, you can achieve this effect by using CSS to style additional SVG elements like <rect>
or by applying styles through external, internal, or inline CSS.
Inline CSS – Understanding the Pitfalls
You can intuitively attempt to use the style="background-color"
property directly on an <svg>
element, expecting it to work the same way it does for HTML elements like <div>
or <p>
. However, this approach is fraught with pitfalls and misunderstandings. But sometimes it works! In the following example, we use the background-color
property in the style
attribute for <svg>
element:
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Prepare a path to a source SVG file
6 string documentPath = Path.Combine(DataDir, "tulips.svg");
7
8 // Load an SVG document from the file
9 var document = new SVGDocument(documentPath);
10
11 // Get root <svg> element of the document
12 var svgElement = document.RootElement;
13
14 // Create a style attribute for <svg> element
15 svgElement.SetAttribute("style", "background: grey");
16
17 // Save the SVG document
18 document.Save(Path.Combine(OutputDir, "with-background-color.svg"));
Why It Appears to Work?
In some browsers or rendering contexts, applying background-color
to an SVG element may appear to work, because the browser may fill the space allocated to the SVG with the specified color. However, this effect does not occur because the SVG itself has a background, but because the area around or behind the SVG content is colored. This is likely an accidental behavior, rather than a feature defined by the
SVG specification.
The Problem with This Approach
The main problem with using background-color
in the SVG style
attribute is that it is not part of the SVG specification. The SVG standard does not recognize background-color
as a valid style property for an SVG element. This means:
- What works in one browser may not work in another.
- The background is not actually part of the SVG content, so you have less control over its behavior and appearance, especially when the SVG is exported, printed, or processed in other contexts.
Internal CSS
Internal CSS refers to styles that are embedded directly into an HTML or SVG document, typically in a <style>
tag. This allows you to define specific styles that apply only to the current document, without affecting other documents or requiring external style sheets.
In the following example,
- the
<style>
element is created and added to the SVG to define a CSS class.background
that sets the SVG background color; - the
<rect>
element is created with itsclass
attribute set tobackground
, which applies the grey fill defined in the CSS; - the
<style>
element is inserted first, followed by the<rect>
element, ensuring the rectangle acts as a background for the SVG.
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Set SVG Namespace URL
6 string SvgNamespace = "http://www.w3.org/2000/svg";
7
8 // Load an SVG document from the file
9 var document = new SVGDocument(Path.Combine(DataDir, "tulips.svg"));
10
11 // Get the root <svg> element of the document
12 var svgElement = document.RootElement;
13
14 // Create a <style> element
15 var styleElement = (SVGStyleElement)document.CreateElementNS(SvgNamespace, "style");
16
17 // Set the CSS content to define a background color class
18 styleElement.TextContent = @".background {fill: grey;}";
19
20 // Insert the <style> element at the beginning of the <svg> element
21 svgElement.InsertBefore(styleElement, svgElement.FirstChild);
22
23 // Create a rectangle element and set the class to "background"
24 var rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
25 rectElement.X.BaseVal.Value = 0;
26 rectElement.Y.BaseVal.Value = 0;
27 rectElement.SetAttribute("width", "100%");
28 rectElement.SetAttribute("height", "100%");
29 rectElement.SetAttribute("class", "background");
30
31 // Add the rectangle element as the first child to the <svg> element, after the <style> element
32 svgElement.InsertBefore(rectElement, svgElement.ChildNodes[1]);
33
34 // Save the SVG document
35 document.Save(Path.Combine(OutputDir, "add-background-color-with-css.svg"));
This approach allows for a clean separation of styling and structure, leveraging CSS for easier management and potential future changes to the SVG’s background color. Internal CSS is widely supported across all modern browsers, ensuring consistent rendering of your SVG images.
The figure shows the visualization of the original SVG file (a) and the same file with the added background color (b):
Change Background Color Using SVG Builder
In the following code, the
SVG Builder programmatically adds a background color to an existing SVG document (for tulips.svg
file as in the previous case).
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Initialize an SVG document
6 using (var document = new SVGDocument(Path.Combine(DataDir, "tulips.svg")))
7 {
8 var svg = new SVGSVGElementBuilder()
9 .Width(100, LengthType.Percentage)
10 .Height(100, LengthType.Percentage)
11 .Build(document.FirstChild as SVGSVGElement);
12
13 // Create a new <g> element using SVGGElementBuilder and add <style> and <rect> elements to it
14 var g = new SVGGElementBuilder()
15 .Id("backgound")
16 .AddStyle(style => style
17 .Type("text/css")
18 .AddRule(".background", r => r.Fill(Color.AliceBlue))
19 )
20 .AddRect(rect => rect
21 .X(0).Y(0).Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
22 .Class("background")
23 ).BuildElement(document);
24 svg.InsertBefore(g, svg.FirstElementChild);
25
26 // Save the document
27 document.Save(Path.Combine(OutputDir, "add-background-color-with-builder.svg"));
28 }
The key step in the code involves using SVGGElementBuilder
to define a group element (<g>
) that includes a <style>
element with internal CSS. This CSS defines a background color via the .background
class. A <rect>
element is then added to apply the background using this class. The group is inserted at the beginning of the SVG, effectively setting the background color.
In the chapter SVG Builder – Advanced SVG Creation and Modification, you will find a guide to manipulating SVG effectively using Aspose.SVG Builder API, covering aspects from creating basic elements to advanced techniques such as mixins and syntactic sugar.
Add Background Color for SVG Image Inside HTML
To continue following this tutorial, you should install and configure the Aspose.HTML for .NET library in your C# project.
When working with HTML documents that contain SVG images, you may need to add a background color to your SVG elements. Although SVGs are typically transparent, adding a background can improve visibility and aesthetics. The following C# example shows how to programmatically add a background color to all SVG elements in an HTML document using C# and the Aspose.HTML library for .NET.
- Use one of the HTMLDocument() constructors to load an HTML file.
- Employ the
QuerySelector() method to find the
<style>
element within the HTML document where you will add a new CSS rule. - Use
InnerHTML property to output the current content of the
<style>
element to ensure no important rules are overwritten. - Update the
TextContent property of the
<style>
element to append a CSS rule for setting the background color of SVG elements. - Use the Save() method to export the updated HTML document to a new file.
The source HTML file
aspose-svg.html contains internal CSS. To add a color background for all SVG images, we will inspect the current content of the <style>
element and add a style rule to the SVG elements specifying the background color that will be applied to all SVG images in the HTML file.
1using System.IO;
2using Aspose.Html;
3...
4
5 // Prepare a path to a source HTML file with SVG image
6 string documentPath = Path.Combine(DataDir, "aspose-svg.html");
7
8 // Load an HTML document from the file
9 var document = new HTMLDocument(documentPath);
10
11 // Find a <style> element and assign a background color value for all svg elements
12 var styleElement = document.QuerySelector("style");
13
14 // Print content of the <style>
15 Console.WriteLine(styleElement.InnerHTML);
16
17 // Assign a text content for the style element
18 styleElement.TextContent = styleElement.InnerHTML + "svg {background-color: #fef4fd;}";
19
20 // Save the HTML document
21 document.Save(Path.Combine(OutputDir, "with-background-color.html"));
The figure shows the visualization of the original HTML file and the same file with the added background color for SVG image:
Change Background Color Using JavaScript
SVG Document
To dynamically add a background color to an SVG file using JavaScript, you can embed a <script>
element directly into the SVG. Here’s a step-by-step guide on how to accomplish this:
- Use the SVGDocument class to load an SVG file.
- Access the root
<svg>
element from the loaded document. This is the element to which you will add the background. - Use the
CreateElementNS() method to create a new
<script>
element. This script will contain JavaScript code to add an SVG background color. - Define JavaScript code. Select the SVG element, create a
<rect>
with full dimensions and background color, and insert it as the first child to set the background. - Add the newly created
<script>
element to the SVG document. - Save the updated SVG document with the embedded JavaScript code, which now includes the background color logic.
1using Aspose.Svg;
2using System.IO;
3...
4
5 // Prepare the path to the SVG document
6 string documentPath = Path.Combine(DataDir, "tree.svg");
7
8 // Load the SVG document from the file
9 var document = new SVGDocument(documentPath);
10
11 // Get the root <svg> element of the document
12 var svgElement = document.RootElement;
13
14 // Create a new <script> element
15 var scriptElement = document.CreateElementNS("http://www.w3.org/2000/svg", "script");
16
17 // Define JavaScript code to add a <rect> element as the background
18 scriptElement.TextContent = @"
19 var svgElement = document.getElementsByTagName('svg')[0];
20 if (svgElement) {
21 var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
22 rectElement.setAttribute('x', '0');
23 rectElement.setAttribute('y', '0');
24 rectElement.setAttribute('width', '100%');
25 rectElement.setAttribute('height', '100%');
26 rectElement.setAttribute('fill', '#fef4fd');
27 svgElement.insertBefore(rectElement, svgElement.firstChild);
28 };
29 ";
30
31 // Append the <script> element to the SVG document
32 svgElement.AppendChild(scriptElement);
33
34 // Save the modified SVG document
35 document.Save(Path.Combine(OutputDir, "svg-background-color-using-script.svg"))
SVG Inside HTML Document
To continue following this tutorial, you should install and configure the Aspose.HTML for .NET library in your C# project.
To change the background color of an SVG image inside HTML document using JavaScript with Aspose.HTML for .NET, you can embed JavaScript directly within the SVG code and then use Aspose.HTML to execute the script. Below is how you can achieve this:
- Load an HTML Document using the HTMLDocument() constructor.
- Use the QuerySelector() to find the SVG element by its ID or another attribute.
- Use the
CreateElement() method to create a new
<script>
element. Set its TextContent to JavaScript code that modifies the SVG’s background color. - Append the new
<script>
element to the document’s body using theAppendChild()
method, ensuring the JavaScript code is executed. - Include a conditional check to handle cases where the SVG element is not found, outputting a relevant message if necessary.
- Use the Save() method to export the updated HTML document with the embedded script to a new file.
1using Aspose.Html;
2using System.IO;
3...
4
5 // Prepare a path to a source HTML file with SVG image
6 string documentPath = Path.Combine(DataDir, "aspose-svg.html");
7
8 // Load an HTML document from the file
9 var document = new HTMLDocument(documentPath);
10
11 // Find the SVG element by its ID (or any other attribute)
12 var svgElement = document.QuerySelector("svg[id='mySvg']");
13
14 if (svgElement != null)
15 {
16 // Create a new <script> element
17 var scriptElement = document.CreateElement("script");
18
19 // Define JavaScript code to add a <rect> element as the background
20 scriptElement.TextContent = @"
21 var svgElement = document.getElementById('mySvg');
22 if (svgElement) {
23 var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
24 rectElement.setAttribute('x', '0');
25 rectElement.setAttribute('y', '0');
26 rectElement.setAttribute('width', '100%');
27 rectElement.setAttribute('height', '100%');
28 rectElement.setAttribute('fill', '#fef4fd');
29 svgElement.insertBefore(rectElement, svgElement.firstChild);
30 };
31 ";
32
33 // Append the <script> element to the HTML document's body
34 document.Body.AppendChild(scriptElement);
35 }
36 else
37 {
38 // Handle the case where the svgElement was not found
39 Console.WriteLine("SVG element not found.");
40 }
41
42 // Save the SVG document
43 document.Save(Path.Combine(OutputDir, "svg-background-color-html-script.html"));
Conclusion
In this article, we looked at several methods for applying and changing the background color of SVG images using the Aspose.SVG for .NET and Aspose.HTML for .NET libraries:
- The most robust and standards-compliant approach is to modify the SVG document directly. Adding a
<rect>
element as the SVG’s first child creates a solid background that underlies all other graphic elements. This method is especially useful, ensuring a consistent appearance and compatibility across all rendering contexts. - For scenarios where SVG images are embedded within HTML documents, CSS and JavaScript can be employed to style the SVG background. However, due to varying browser behaviors, JavaScript may not be as portable or reliable.
In summary, the method you choose should depend on the context in which the SVG will be used and the level of control and consistency required. Modifying the SVG directly is generally the most reliable method, especially for stand-alone SVG files. When working with SVG in HTML documents, CSS and JavaScript provide flexibility but with potential limitations.
See Also
- How to add new SVG elements and set their color properties, we covered in detail C# examples in the article Edit SVG Files.
- The SVG Background Color article discusses what background is in SVG. It also provides SVG code examples and a comprehensive guide on how to set or change a background color.
- The article SVG Color looks at how SVG text and shapes can be colorized. You’ll find an overview of how color is defined, including the various ways you can control the transparency of SVG content.
- You can download the complete examples and data files from GitHub. About downloading from GitHub and running examples, you find out from the section How to Run the Examples.
- Color Converter is a free online application for transforming colors between color formats. Just enter color code and get the result at once! You don’t need any additional software. Try our forceful Color Converter just now!