Change HTML Background Color in Java

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

The CSS background-color property can style one element, a group of elements, or the entire webpage. Use inline CSS for a specific element and an internal stylesheet when a selector should apply the same rule across the document.

This article provides Java examples for changing the background of one paragraph and the whole page with Aspose.HTML for Java.

Change the Background Color of One Element

The following example uses background-color.html, selects the first paragraph, adds an inline background color, and saves the edited document as background-color-element.html.

  1. Download background-color.html to the application’s working directory.
  2. Load the file into an HTMLDocument.
  3. Select the first paragraph with querySelector().
  4. Set its style attribute to background-color: #e5f3fd; with setAttribute().
  5. Save the modified document under a new file name.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.Element;
 3
 4String inputPath = "background-color.html";
 5String outputPath = "background-color-element.html";
 6
 7HTMLDocument document = new HTMLDocument(inputPath);
 8Element paragraph = document.querySelector("p");
 9
10if (paragraph != null) {
11    paragraph.setAttribute("style", "background-color: #e5f3fd;");
12}
13
14document.save(outputPath);

Only the first paragraph receives the light-blue background. Change the selector to target another element, such as h1, .notice, article p, or table.

Calling setAttribute("style", value) replaces the element’s complete inline style. If the element already has declarations that must be preserved, include them in the new value or update only the required property through the CSS DOM.

Change the Background Color of the Whole Page

Set background-color on the document <body> to change the page background. The next example uses inline CSS and saves the result as background-color-page-inline.html.

  1. Load the source HTML file.
  2. Retrieve the document body.
  3. Set the body’s style attribute with the required background color.
  4. Save the updated document.
 1import com.aspose.html.HTMLDocument;
 2
 3String inputPath = "background-color.html";
 4String outputPath = "background-color-page-inline.html";
 5
 6HTMLDocument document = new HTMLDocument(inputPath);
 7document.getBody().setAttribute(
 8        "style",
 9        "background-color: #e5f3fd;"
10);
11
12document.save(outputPath);

Use this approach for a direct change to one page. For reusable or selector-based styling, add an internal or external stylesheet instead.

Change the Page Background Using Internal CSS

Internal CSS is stored in a <style> element inside the document <head>. This keeps the declaration separate from the page content and allows several selectors to be managed together.

  1. Load the HTML file.
  2. Create a <style> element with createElement().
  3. Set its text to a CSS rule for the document body.
  4. Append the style element to <head>.
  5. Save background-color-page-internal.html.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.Element;
 3
 4String inputPath = "background-color.html";
 5String outputPath = "background-color-page-internal.html";
 6
 7HTMLDocument document = new HTMLDocument(inputPath);
 8Element style = document.createElement("style");
 9
10style.setTextContent("body { background-color: rgb(229, 243, 253); }");
11document.querySelector("head").appendChild(style);
12
13document.save(outputPath);

The RGB value in this example represents the same light-blue color as #e5f3fd. If the body already has an inline background-color, that declaration will normally take precedence over a normal internal rule. Remove or update the inline property when the internal stylesheet should control the result.

CSS Background Color Values

The background-color property accepts the same CSS color formats used by the foreground color property:

FormatExample
Named colorbackground-color: aliceblue;
HEXbackground-color: #e5f3fd;
RGBbackground-color: rgb(229, 243, 253);
HSLbackground-color: hsl(207, 80%, 95%);
RGB with alphabackground-color: rgba(229, 243, 253, 0.8);
Transparentbackground-color: transparent;

An alpha value makes the element background partially transparent; it does not make the text transparent. The visible result then depends on the colors and content behind the element.

Inline CSS vs. Internal CSS

RequirementRecommended approach
Change one particular elementInline CSS on that element
Set a direct page backgroundInline CSS on <body>
Style several matching elementsInternal CSS with an appropriate selector
Share styling between multiple HTML filesExternal stylesheet

When foreground text is displayed over the new background, verify that the combination remains readable. See Check Color Contrast in Java for programmatic accessibility validation.

Common Background Color Issues

IssueCause and fix
The background color does not changeConfirm that the selector matches and that another declaration does not win in the CSS cascade.
Only one element changesquerySelector() returns the first match. Use a shared CSS rule or querySelectorAll() when every matching element must be updated.
Existing inline styles disappearSetting the complete style attribute replaces its earlier contents. 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.
A translucent background looks unexpectedAlpha colors blend with the content behind the element. Check the underlying background and opacity value.
Text becomes difficult to readChoose foreground and background colors with sufficient contrast and validate the result.
The saved file is unchangedDOM edits remain in memory until document.save() is called. Verify that you opened the output file rather than the original input.

FAQ

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

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 a div or paragraph?

Select the element with querySelector() 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 element’s background area.

Why does inline background color override internal CSS?

A normal inline declaration generally has greater specificity than normal rules 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, such as rgba(229, 243, 253, 0.8), for partial transparency.

Is CSS background-color the same as PdfSaveOptions background color?

No. CSS background-color belongs to the HTML content and applies to the selected element. PdfSaveOptions.setBackgroundColor() fills the output PDF page behind the rendered document content.

Related Articles