Check Color Contrast in Java

Use the Aspose.HTML for Java accessibility API to check HTML against WCAG 2.0 contrast criteria. Select criteria 1.4.3 and 1.4.6, create an AccessibilityValidator, validate the HTMLDocument, and inspect reported elements whose text contrast fails the selected checks.

Color Contrast Requirements in WCAG 2.0

Sufficient contrast between text and its background makes content easier to read, especially for users with low vision. WCAG 2.0 addresses text contrast under guideline 1.4 – Distinguishable. A contrast ratio ranges from 1:1 for identical colors to 21:1 for black and white.

The examples on this page use two WCAG 2.0 success criteria:

In WCAG 2.0, large-scale text is at least 18 pt, or at least 14 pt when bold. These criteria include exceptions such as logos and incidental text; consult the linked WCAG criteria when evaluating conformance.

Prepare HTML for Contrast Checking

The following preview contains one text block with strong contrast and another with poor contrast:

Text with good contrast
Text with bad contrast

Save the corresponding HTML as check-color.html to use it with both Java examples:

 1<html>
 2    <head>
 3        <style>
 4            div {
 5                font-family: sans-serif;
 6                text-align: center;
 7                font-weight: bold;
 8                text-align: center;
 9                padding: 10px;
10                border-radius: 15px;
11                width: 300px;
12                margin: auto;
13            }
14            .bad {
15                background-color: #8b030e;
16                font-size: 16px;
17            }
18            .good {
19                background-color: #fff0f2;
20                font-size: 18px;
21            }
22        </style>
23    </head>
24    <body>
25        <div class="good">Text with good contrast</div>
26        <div class="bad">Text with bad contrast</div>
27    </body>
28</html>

Check Multiple Color Contrast Criteria in Java

The first Java example validates the document against both minimum and enhanced text-contrast criteria:

  1. Create a WebAccessibility instance and retrieve principle 1, Perceivable, followed by guideline 1.4, Distinguishable.
  2. Obtain criteria 1.4.3 and 1.4.6 with Guideline.getCriterion().
  3. Add both Criterion objects to the rule list.
  4. Create an AccessibilityValidator with the selected rules and ValidationBuilder.getAll().
  5. Load the source file into an HTMLDocument and call validate().
  6. If validation is unsuccessful, output the formatted result with ValidationResult.saveToString().
 1// Validate HTML accessibility for color contrast in Java using WCAG criteria
 2
 3// Prepare a path to a source HTML file
 4String documentPath = "check-color.html";
 5
 6// Create a WebAccessibility instance
 7WebAccessibility webAccessibility = new WebAccessibility();
 8
 9// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
10Guideline guideline = webAccessibility.getRules()
11        .getPrinciple("1").getGuideline("1.4");
12
13// Get criterion by code, for example 1.4.3
14Criterion criterion143 = guideline.getCriterion("1.4.3");
15
16// Get criterion by code, for example 1.4.6
17Criterion criterion146 = guideline.getCriterion("1.4.6");
18
19// Create an accessibility validator for the selected criteria
20// and enable all validation settings
21List<IRule> rules = new List<>();
22rules.add(criterion143);
23rules.add(criterion146);
24
25AccessibilityValidator validator = webAccessibility.createValidator(
26        rules,
27        ValidationBuilder.getAll()
28);
29
30final HTMLDocument document = new HTMLDocument(documentPath);
31ValidationResult validationResult = validator.validate(document);
32if (!validationResult.getSuccess()) {
33    System.out.println(validationResult.saveToString());
34}

The example prints a formatted validation result only when at least one selected check is unsuccessful. It is useful when you need results for both Level AA and Level AAA text-contrast criteria in one run.

Check One Color Contrast Criterion

The second example checks only criterion 1.4.3 and traverses unsuccessful technique results to obtain error messages and affected HTMLElement objects:

  1. Retrieve guideline 1.4 from principle 1.
  2. Call getCriterion() with code 1.4.3.
  3. Pass the criterion and ValidationBuilder.getAll() to createValidator().
  4. Load and validate the HTML document.
  5. Iterate through unsuccessful RuleValidationResult and ITechniqueResult objects.
  6. For an HTMLElement target, print the failed technique code, error message, and element markup.
 1// Check color contrast on an HTML document using Java
 2
 3// Prepare a path to a source HTML file
 4String documentPath = "check-color.html";
 5
 6// Create a WebAccessibility instance
 7WebAccessibility webAccessibility = new WebAccessibility();
 8
 9// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
10Guideline guideline = webAccessibility.getRules()
11        .getPrinciple("1").getGuideline("1.4");
12
13// Get criterion by code, for example 1.4.3
14Criterion criterion = guideline.getCriterion("1.4.3");
15
16// Create an accessibility validator for the selected criterion
17// and enable all validation settings
18AccessibilityValidator validator = webAccessibility.createValidator(
19        criterion,
20        ValidationBuilder.getAll()
21);
22
23final HTMLDocument document = new HTMLDocument(documentPath);
24ValidationResult validationResult = validator.validate(document);
25if (!validationResult.getSuccess()) {
26    // Get all result details
27    for (RuleValidationResult ruleResult : validationResult.getDetails()) {
28        // If the result of the rule is unsuccessful
29        if (!ruleResult.getSuccess()) {
30            // Get errors list
31            for (ITechniqueResult result : ruleResult.getErrors()) {
32                // Check the type of the erroneous element, in this case
33                // we have an error in the html element rule
34                if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
35                    // Element of file with error
36                    HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
37
38                    System.out.println(String.format("Error in rule %s : %s",
39                            result.getRule().getCode(), result.getError().getErrorMessage()));
40
41                    System.out.println(String.format("HTML Element: %s",
42                            rule.getOuterHTML()));
43                }
44            }
45        }
46    }
47}

For the sample HTML, an unsuccessful check can produce output similar to the following. The current example labels the returned element as CSS Rule, although the object is an HTMLElement:

1Error in rule G18 : Make sure the contrast ratio between the text (and images of text) and the background behind the text is at least 4.5:1 for text less than 18 points if it is not in bold,
2and less than 14 points if it is in bold.
3CSS Rule: <div class="bad">Text with bad contrast</div>

Improve Color Contrast Accessibility

  1. Meet the contrast threshold for the selected WCAG level and use the correct large-scale text definition.
  2. Prefer actual text to images of text so users can resize and restyle the content.
  3. Do not use color as the only visual means of conveying information; add text, icons, patterns, or other cues.
  4. Choose combinations that remain distinguishable for users with different forms of color-vision deficiency.
  5. Check placeholder text and text shown in different interaction states when those elements are covered by the applicable criterion.
  6. Combine automated checks with manual review because page states, images, and complex backgrounds may require human evaluation.

Common Color Contrast Issues

IssueExplanation and fix
Treating every failure from the combined example as a Level AA failureThe example checks both 1.4.3 at Level AA and the stricter 1.4.6 at Level AAA. Inspect the failed rule code to determine which level was not met.
Assuming any bold text qualifies as large-scale textUnder WCAG 2.0, bold text must be at least 14 pt to use the large-scale contrast threshold. Non-bold text must be at least 18 pt.
Using sufficient contrast but relying on color aloneContrast and use of color are separate accessibility concerns. Add text, icons, patterns, or another visual cue when color conveys meaning.
Treating an automated result as proof of complete conformanceAutomated validation covers the selected rules and detectable document state. Review interactive states and visually complex content manually.

FAQ

Which WCAG color contrast criteria can I check with these examples?

The examples retrieve WCAG 2.0 criterion 1.4.3 for minimum text contrast and 1.4.6 for enhanced text contrast. You can validate both criteria together or pass one Criterion object to WebAccessibility.createValidator().

Why can text pass Level AA but fail Level AAA?

Level AAA uses stricter thresholds. Normal text requires 4.5:1 for Level AA but 7:1 for Level AAA; large-scale text requires 3:1 for AA and 4.5:1 for AAA.

Does passing the color contrast check guarantee WCAG conformance?

No. It confirms only that the tested content passed the selected automated rules. Complete accessibility evaluation also requires other WCAG criteria and manual testing.

WCAG Contrast References

Related Articles

Try the Online Color Contrast Checker

Use the free online Color Contrast Checker to calculate the contrast ratio for a foreground and background color pair and compare it with WCAG thresholds.

Color Contrast Checker