How to Change Text Color in HTML using Python – Inline and Internal CSS Examples

Why Change Text Color Programmatically?

Dynamically changing text color is a common task in web automation, reporting, and document generation. With Aspose.HTML for Python via .NET, you can safely load, modify, and save HTML files without manual editing. This approach is especially useful when you need to:

To change the text color on a web page is easy with the CSS color property. There are a few ways you can set this property value. You can use inline, internal or external CSS, and HTML color values may be specified as the standard English color names or with HEX, RGB, RGBA, HSL, and HSLA values.

This article shows how to programmatically change text color with Aspose.HTML for Python via .NET, using both inline and internal CSS.

Change Text Color Using Inline CSS

In this example, we set the text color directly in the style attribute of an HTML element. This is known as inline CSS. This method is simple and ideal for quickly styling individual elements.

For example, in the following code snippet, you can see how to specify the CSS color property for HTML <p> element in an HTML file. Take a few steps:

  1. Load an existing HTML document using HTMLDocument().
  2. Find, for example, the first paragraph <p> element to set a style attribute. Use the get_elements_by_tag_name(name) method that returns the first element with a given tag name in document order.
  3. Use the set_attribute() method to set the style attribute with color property.
  4. Save the modified HTML document to the output directory.
 1# Change HTML text color using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Setup directories and define paths
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10save_path = os.path.join(output_dir, "change-text-color-inline-css.html")
11document_path = os.path.join(data_dir, "file.html")
12
13# Create an instance of an HTML document
14with ah.HTMLDocument(document_path) as doc:
15    # Find the first paragraph element
16    paragraph = doc.get_elements_by_tag_name("p")[0]
17
18    # Set the style attribute with color property
19    paragraph.set_attribute("style", "color: #8B0000;")
20
21    # Save the modified HTML document to a file
22    doc.save(save_path)

Inline CSS works best when you want to change the style of specific elements individually. As a result, the text of the first paragraph in the HTML file will be recolored to #8B0000 DarkRed color ( to see figure (a), please scroll down the page).

Change Text Color Using Internal CSS

Internal CSS is ideal when you want to apply uniform styles to multiple elements, like all paragraphs or headers. In this example, we will add a <style> block to the <head> section of an HTML document. This approach is cleaner and ideal when you need to style multiple elements consistently.

  1. Load an HTML document.
  2. Create a new <style> element and assign the text color value for all <p> elements. Use the create_element(local_name) method that creates an element of the type specified.
  3. Use the get_elements_by_tag_name() method to find the document’s <head> element and append <style> element to it.
  4. Save the modified HTML document.
 1# Change color for all paragraphs in HTML using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Prepare an output path for saving the document
 7output_dir = "output"
 8os.makedirs(output_dir, exist_ok=True)
 9save_path = os.path.join(output_dir, "change-text-color-internal-css.html")
10
11# Prepare a 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    # Create a <style> element and set CSS for the all <p> elements
18    style = doc.create_element("style")
19    style.text_content = "p { color: #8B0000 }"
20
21    # Find the <head> element and append the <style> element
22    head = doc.get_elements_by_tag_name("head")[0]
23    head.append_child(style)
24
25    # Save the modified HTML document to a file
26    doc.save(save_path)

To change text color, you can use the Python examples considered in this article with HTML <p>, <h1>, or <h2> elements, etc. Keep in mind that using the style attribute (inline CSS) overrides any style specified in the HTML <style> tag or in an external style sheet.

The figure illustrates the results of changing text color according to the usage of inline CSS example (a) and internal CSS example (b):

Text “Two fragments of the HTML document with colored paragraph text.”

Dynamically Change Text Color Based on Condition

In some cases, you may need to dynamically change text color based on data, for example, to highlight scores, alerts, or warnings. Using Aspose.HTML for Python via .NET, you can easily access and change HTML elements based on their content or attributes. The following example demonstrates how to set text color based on a numeric value:

 1# Change text color based on data in HTML using Python
 2
 3import os
 4import aspose.html as ah
 5
 6output_dir = "output"
 7os.makedirs(output_dir, exist_ok=True)
 8save_path = os.path.join(output_dir, "conditional-text-color.html")
 9
10html_content = """
11<html>
12<body>
13<p>Score: 85</p>
14<p>Score: 42</p>
15<p>Score: 73</p>
16</body>
17</html>
18"""
19
20# Initialize the HTML document
21with ah.HTMLDocument(html_content, ".") as doc:
22    paragraphs = doc.get_elements_by_tag_name("p")
23
24    for p in paragraphs:
25        text = p.text_content
26        score = int(text.split(":")[1].strip())
27
28        # Apply color conditionally
29        color = "green" if score >= 70 else "red"
30        p.set_attribute("style", f"color: {color};")
31
32    # Save the modified document
33    doc.save(save_path)

The code reads the text values ​​of a paragraph. It extracts the numeric score and compares it to a reference value. Each <p> element gets a style applied dynamically based on that condition. This technique is useful when creating reports or data visualizations in HTML, making the output more readable and visually understandable.

Text “Scores: 85 (green), 42 (red), 73 (green).”

Best Practices

FAQ

1. What is the difference between inline and internal CSS?
Inline CSS is applied directly to a single element using the style attribute, while internal CSS is applied to multiple elements via the <style> block within the <head>.

2. Why doesn’t the text color change in the output?
Make sure the element selector is specified correctly (e.g., “p” for paragraph). Also, please verify that your HTML document structure includes the target element and that styles with higher priority don’t override it.

3. Can I use RGB or HSL values ​​instead of HEX?
Yes. The color property accepts all CSS color formats: color names, HEX (#8B0000), RGB (rgb(139,0,0)), RGBA, HSL, and HSLA.

See Also

  • Working with HTML Color – In this article, you will find HTML code examples of how to change text color.
  • How to change background color? – In this article, you will explore how to change background color for text in paragraphs or entire pages using Aspose.HTML for Python via .NET.
  • 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.

You can download the complete examples and data files from GitHub.

Text “HTML Web Applications”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.