Change HTML Background Color in Python

To change an HTML background color in Python, load the file with HTMLDocument, select the target element, set the CSS background-color property through its style attribute or an internal <style> element, and save the updated document.

Use inline CSS when one specific element needs a different background. Use an internal stylesheet when a selector should apply the same rule across the document. Setting background-color on the <body> element changes the page background.

The property accepts named, HEX, RGB, and HSL color syntaxes, including values with alpha transparency. The examples below use the HEX value #fff0f5 and its RGB equivalent rgb(255 240 245).

Change the Background Color of One Element

The first example loads file.html, selects its first paragraph, gives that paragraph a lavender-blush background with inline CSS, and saves change-background-color-p-inline-css.html.

  1. Load the source HTML into an HTMLDocument.
  2. Select the element whose background must change.
  3. Apply the required CSS background-color value through the element’s inline style attribute.
  4. Save the modified HTML document.
 1# Change paragraph background color in HTML in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare input and output paths
 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
11data_dir = "data"
12document_path = os.path.join(data_dir, "file.html")
13
14# Change the first paragraph background color
15with ah.HTMLDocument(document_path) as document:
16    paragraph = document.get_elements_by_tag_name("p")[0]
17
18    # Set the style attribute with background-color property
19    paragraph.set_attribute("style", "background-color: #fff0f5;")
20
21    document.save(save_path)

Only the first paragraph receives the new background. The example writes a complete new style attribute. If the paragraph already has inline declarations such as color or font-size, they will be removed. Use paragraph.style.background_color = "#fff0f5" when only the background property should be updated.

Change the Page Background Using Inline CSS

Set background-color on the document <body> to change the background of the entire page. The next example updates only the body’s background_color CSS property and saves change-background-color-inline-css.html.

  1. Load the source HTML file.
  2. Access the document <body> element through document.body.
  3. Set the required page color through body.style.background_color.
  4. Save the modified document.
 1# Change HTML background color with inline CSS in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare input and output paths
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10
11document_path = os.path.join(data_dir, "file.html")
12save_path = os.path.join(output_dir, "change-background-color-inline-css.html")
13
14# Change the body background color
15with ah.HTMLDocument(document_path) as document:
16    document.body.style.background_color = "lavenderblush"
17    document.save(save_path)

The image compares the two inline CSS results. Example a) changes only the first paragraph, while example b) changes the complete page background:

HTML paragraph and page backgrounds changed with inline CSS in Python

Change the Page Background Using Internal CSS

Internal CSS stores the page background rule in a <style> element inside the document <head>. The following rule produces the same lavender-blush page background:

1<head>
2<style>
3	body {
4	background-color: rgb(255 240 245);
5	}
6</style>
7</head>

The Python example calls remove_property("background-color") before adding the internal rule. This removes only that inline CSS property and preserves other declarations. The step is necessary when an inline background is present and the internal stylesheet should control the result, because a normal inline declaration generally takes precedence over a normal internal rule.

  1. Load the source HTML into an HTMLDocument.
  2. Remove or update any inline background declaration that should not override the new internal rule.
  3. Create a <style> element with create_element().
  4. Define a CSS rule for the required page or elements and append the style element to <head>.
  5. Save the modified HTML document.
 1# Change HTML background color with internal CSS in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare input and output paths
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10
11document_path = os.path.join(data_dir, "file.html")
12save_path = os.path.join(output_dir, "change-background-color-internal-css.html")
13
14# Change the body background color using internal CSS
15with ah.HTMLDocument(document_path) as document:
16    # Remove only the inline background-color property
17    document.body.style.remove_property("background-color")
18
19    # Create an internal CSS rule
20    style = document.create_element("style")
21    style.text_content = """
22        body {
23            background-color: rgb(255 240 245);
24        }
25    """
26
27    head = document.get_elements_by_tag_name("head")[0]
28    head.append_child(style)
29
30    document.save(save_path)

The saved page has the same background shown in result b) above, but the color is defined in the document stylesheet instead of the body’s inline style attribute.

Change the Background Color of Table Cells

The final example loads table.html, collects all <td> elements, applies alternating lavender and white backgrounds in document order, and saves change-table-cell-background.html.

  1. Load the HTML document containing the table.
  2. Select the table cells that require background styling.
  3. Iterate through the cells using an index or another appropriate condition.
  4. Apply the required alternating or condition-based background colors.
  5. Save the modified HTML document.
 1# Change table cell background colors in HTML in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare input and output paths
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10
11document_path = os.path.join(data_dir, "table.html")
12save_path = os.path.join(output_dir, "change-table-cell-background.html")
13
14# Change alternating table cell background colors
15with ah.HTMLDocument(document_path) as document:
16    # Select all <td> elements
17    cells = document.get_elements_by_tag_name("td")
18
19    # Loop through each table cell and set alternating background colors
20    for i in range(cells.length):
21        cell = cells[i]
22        color = "#f3d2dd" if i % 2 == 0 else "#ffffff"
23        cell.set_attribute("style", f"background-color: {color};")
24
25    document.save(save_path)

The output alternates the background color of consecutive data cells. It does not alternate complete rows because the condition uses the position of each cell in the full <td> collection.

HTML table with alternating lavender and white cell backgrounds

Common Background Color Issues

IssueCause and recommended action
The background color does not changeVerify that the selected element exists and that another declaration does not take precedence in the CSS cascade.
Only one element changesThe example selects one element or indexes one collection item. Iterate over all required elements or add a shared CSS rule.
Existing inline styles disappearSetting the complete style attribute replaces its previous declarations. Preserve the required declarations or update only one CSS property.
An internal body rule has no visible effectThe body may already have an inline background declaration. Remove or update that inline property when the stylesheet should control the result.
Unexpected table cells receive colorThe example alternates individual <td> elements in document order, not rows or columns. Change the selection and condition for the required pattern.
A translucent background looks unexpectedA color with an alpha component blends with the content behind the element. Check the underlying background and alpha value.
Changes are missing from the fileDOM changes remain in memory until save() is called. Verify the output path and open the saved document.

FAQ

How do I change the background color of an HTML page in Python?

Set the CSS background-color property on the document <body>, either through its inline style attribute or through a body rule in an internal stylesheet, and save the document.

How do I change the background color of one element?

Select the required element and set its inline background-color, or create a CSS rule that matches its tag, class, ID, or another stable attribute.

What is the difference between color and background-color?

The CSS color property controls foreground text, while background-color paints the background area of the selected element.

Why does an inline background color override internal CSS?

A normal inline declaration generally has greater specificity than normal declarations in internal or external stylesheets. Update or remove the inline property when the stylesheet should control the element.

How do I make an HTML background transparent?

Use background-color: transparent for full transparency or a color with an alpha component for partial transparency.

Can I convert the edited HTML to PDF or an image?

Yes. Save the modified HTML or pass the document to the appropriate conversion workflow described in Converting Between Formats.

Related Articles

Other Platforms