How to change background color in HTML using Python
Let’s say you are creating an HTML report and want to highlight important sections with a different background color. Aspose.HTML for Python via .NET allows you to programmatically change inline and internal styles without changing the source code.
This article demonstrates three practical ways to change the background color of an HTML document using the Aspose.HTML for Python via .NET library, and provides ready-made Python code snippets for practical use. Here you цшll learn how to:
- Change the background color of a specific HTML element (such as a paragraph).
- Change the background color of an entire web page.
- Dynamically apply a background color to table cells.
Changing the background color of an HTML is easy with the CSS background-color property. You can use inline, internal, or external CSS, and HTML color values can be specified as standard
color names or in HEX, RGB, RGBA, HSL, and HSLA formats. In the examples below, we will use HEX and RGB color codes, as they are among the most commonly used.
Change Background Color of Specific Element
Steps to change background color for HTML element using Python:
- Load or create an HTML document.
- Determine which element (
<p>,<body>, etc.) you want to change the background color for and find this element to set a style attribute for it. Use the get_elements_by_tag_name(name) method of the Element class that returns HTML element with a given tag name. - Use the set_attribute(“style”, “…”) method to apply inline CSS.
- Save the modified HTML to a file.
The following Python example shows the background color change for the first <p> element:
1# Change background color for HTML paragraph using Python
2
3import os
4import aspose.html as ah
5
6# Prepare output path for document saving
7output_dir = "output/"
8os.makedirs(output_dir, exist_ok=True)
9save_path = os.path.join(output_dir, "change-background-color-p-inline-css.html")
10
11# Prepare path to the source HTML file
12data_dir = "data/"
13document_path = os.path.join(data_dir, "file.html")
14
15# Create an instance of an HTML document
16with ah.HTMLDocument(document_path) as doc:
17 # Find the first paragraph element
18 paragraph = doc.get_elements_by_tag_name("p")[0]
19
20 # Set the style attribute with background-color property
21 paragraph.set_attribute("style", "background-color: #fff0f5;")
22
23 # Save the modified HTML document to a file
24 doc.save(save_path)As a result, the first paragraph will have a lavenderblush background (#fff0f5). To see figure (a), please scroll down the page. You can set or change background color for various HTML elements such as <p>, <h1>…<h6>, <div>, <table>, etc.
Change Background Color of the Entire Web Page
You can also change the background color of the entire HTML page by updating the inline CSS style of the <body> element or using internal CSS.
Change Background Color Using Inline CSS
If you want to change the color of the entire HTML document, you should use the background-color property of the style attribute in the opening tag of the <body> section.
HTML code
1<body style="background-color: lavenderblush">Python example
1# Change background color with inline CSS using Python
2
3import os
4import aspose.html as ah
5
6# Define the output path for saving the document
7output_dir = "output/"
8save_path = os.path.join(output_dir, "change-background-color-inline-css.html")
9
10# Define the path to the source HTML file
11data_dir = "data/"
12document_path = os.path.join(data_dir, "file.html")
13
14# Create an instance of an HTML document
15document = ah.HTMLDocument(document_path)
16
17# Find the <body> element to set a style attribute
18body = document.get_elements_by_tag_name("body")[0]
19
20# Set the style attribute with background-color property
21current_style = body.get_attribute("style") or ""
22new_style = current_style + "background-color: lavenderblush"
23body.set_attribute("style", new_style)
24
25# Save the HTML document to a file
26document.save(save_path)Result: The background of the entire page turns lavenderblush (#fff0f5). The figure shows two fragments of the rendered HTML files: (a) with a background color for the first paragraph element; (b) with a changed background color for the entire document:

Change Background Color Using Internal CSS
The same background colorization result for the entire HTML document (as in figure b) can be achieved using internal CSS, as shown in the following HTML code example:
1<head>
2<style>
3 body {
4 background-color: rgb(255 240 245);
5 }
6</style>
7</head>Note: Keep in mind, that the usage of a style attribute overrides any style set in the HTML <style> tag or external style sheet.
The next Python example demonstrates how to realize internal CSS to change background color for a whole HTML file. Take a few steps:
- Load an existing HTML file.
- Find the
<body>element and remove thebackground-colorproperty from thestyleattribute. Note: If the background color is set using inlinestyleattribute, this step is required because using thestyleattribute overrides both internal and external CSS. - Create a
<style>element and assign thebackground-colorvalue for<body>element. - Find the
<head>element in your document and add the<style>element into it. - Save the modified HTML document.
1# Change background color for HTML using internal CSS using Python
2
3import os
4import aspose.html as ah
5
6# Define paths
7output_dir = "output/"
8save_path = os.path.join(output_dir, "change-background-color-internal-css.html")
9data_dir = "data/"
10document_path = os.path.join(data_dir, "file.html")
11
12# Create an instance of an HTML document
13document = ah.HTMLDocument(document_path)
14
15# Find the <body> element
16body = document.get_elements_by_tag_name("body")[0]
17
18# Remove the background-color property from the style attribute
19current_style = body.get_attribute("style") or ""
20updated_style = " ".join(prop for prop in current_style.split(";") if not prop.strip().startswith("background-color"))
21body.set_attribute("style", updated_style)
22
23# Create a <style> element with CSS rules for the background color
24style = document.create_element("style")
25style.text_content = "body { background-color: rgb(255 240 245) }"
26
27# Find the <head> element and append the <style> element
28head = document.get_elements_by_tag_name("head")[0]
29head.append_child(style)
30
31# Save the HTML document to a file
32document.save(save_path)Change Background Color for Table Cells
The following Python example demonstrates how to change the background color of table cells in an HTML document. The code loads an existing HTML file, finds all <td> elements, and applies alternating background colors to each cell using inline CSS. This approach can help highlight rows of data, improve table readability, or visually separate content before converting the document to another format, such as PDF or an image.
1# Change background color for table cells using Python
2
3import os
4import aspose.html as ah
5
6# Prepare directories
7data_dir = "data"
8output_dir = "output"
9os.makedirs(output_dir, exist_ok=True)
10
11# Input and output paths
12document_path = os.path.join(data_dir, "table.html")
13save_path = os.path.join(output_dir, "change-table-cell-background.html")
14
15# Create an instance of the HTML document
16with ah.HTMLDocument(document_path) as doc:
17 # Select all <td> elements
18 cells = doc.get_elements_by_tag_name("td")
19
20 print("Found cells:", cells.length)
21
22 # Loop through each table cell and set alternating background colors
23 for i in range(cells.length):
24 cell = cells[i]
25 color = "#f3d2dd" if i % 2 == 0 else "#ffffff"
26 cell.set_attribute("style", f"background-color: {color};")
27
28 # Save the modified HTML document
29 doc.save(save_path)
30
31print("Saved to:", save_path)
Frequently Asked Questions
1. Is it possible to change the background of only a specific HTML element?
Yes, you can select the desired elements using query_selector() or get_elements_by_tag_name().
2. Does this work with large HTML files?
Yes, Aspose.HTML for Python via .NET efficiently loads and edits even complex HTML documents.
3. Can I use this method to change other styles (font, border, etc.)?
Of course. You can change any CSS property programmatically in the same way.
4. Can I render the modified HTML to PDF or an image?
Yes. Aspose.HTML allows you to convert your modified HTML to PDF, XPS, DOCX, and more formats using the Converter class. Examples of HTML conversion in Python can be found in the chapter
Converting between formats.
See Also
- How to change text color in HTML? – In this article, you will learn how to change color of text in paragraphs, headers, etc., using Aspose.HTML for Python via .NET.
- How to Safely Load and Convert HTML in Python – Sandboxing – In this article, you will learn how to securely load and convert untrusted HTML in Python using Aspose.HTML for Python via .NET. Includes sandbox examples to block scripts and external images.
- How to change border color? – This article gives you information and Python examples on how to add or change border color for your text in an HTML file. Step-by-step examples, CSS tips, and solutions to common styling issues.
- HTML Color Codes – In this article, you will find information about HTML color codes for your website – HTML color names, HEX color codes, RGB, RGBA, HSL and HSLA values.
- Edit HTML Document in Python – In this article, you will explore more HTML editing examples – how to create, populate, add HTML elements, and edit inline and internal CSS.
