Check Color Contrast – Color Contrast Accessibility

If you want to check the website for compliance with WCAG guidelines programmatically, the Aspose.HTML for Java provides the com.aspose.html.accessibility package, which is for all Web Accessibility related manipulations and checks.

This article will discuss color and proper contrast according to WCAG, the world’s authority on web accessibility. You learn how to check color contrast using Aspose.HTML for Java API and make your web content easy to read for all users.

Accessible Color Contrast

Ensuring sufficient color contrast in your web content is essential for creating accessible and user-friendly websites. Poor color contrast can make content difficult to read, especially for users with visual impairments. The Web Content Accessibility Guidelines (WCAG) define minimum contrast ratios to ensure that text is readable by all users. The test criteria for color contrast are contained in the guideline 1.4 – Distinguishable.

For color contrast, WCAG defines two levels of success criteria: AA (minimal contrast) and AAA (enhanced contrast). These criteria checks the contrast ratio between text and its background, which ranges from 1:1 to 21:1.

Below you can see an example of proper contrast between font and background and an example of poor contrast:

Text with good contrast
Text with bad contrast

Let’s write the HTML code for this example to check-color.html file and check color contrast using Aspose.HTML for Java API.

 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 Color Contrast – Java Examples

For visually impaired users, it is necessary to be able to perceive the content on the page normally. The contrast between text and background should be sufficient for its perception. To check the criteria related to contrast checking, find the principle in the code and pass it to the accessibility validator. In the following example, the validator is created for two criteria: 1.4.3 and 1.4.6 from the 1.4 Guideline:

 1// Prepare a path to a source HTML file
 2String documentPath = "check-color.html";
 3
 4// Initialize a webAccessibility container
 5WebAccessibility webAccessibility = new WebAccessibility();
 6
 7// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
 8Guideline guideline = webAccessibility.getRules()
 9        .getPrinciple("1").getGuideline("1.4");
10
11// Get criterion by code, for example 1.4.3
12Criterion criterion143 = guideline.getCriterion("1.4.3");
13
14// Get criterion by code, for example 1.4.6
15Criterion criterion146 = guideline.getCriterion("1.4.6");
16
17// Create an accessibility validator, pass the found guideline
18// as parameters and specify the full validation settings
19List<IRule> rules = new List<>();
20rules.add(criterion143);
21rules.add(criterion146);
22
23AccessibilityValidator validator = webAccessibility.createValidator(
24        rules,
25        ValidationBuilder.getAll()
26);
27
28final HTMLDocument document = new HTMLDocument(documentPath);
29ValidationResult validationResult = validator.validate(document);
30if (!validationResult.getSuccess()) {
31    System.out.println(validationResult.saveToString());
32}

This example demonstrates how to perform a web accessibility check of an HTML document against several WCAG criteria at once — in this case, 1.4.3 (text contrast) and 1.4.6 (enhanced contrast). First, a list of these criteria is created, then validation is run using AccessibilityValidator, and the final result is output as a full-text report. This approach is convenient for quickly assessing a document’s compliance with several rules without in-depth analysis.

Check Color Contrast Against Specific Accessibility Criterion

The following Java code performs a more detailed check for a single criterion (1.4.3). It does not simply validate the document but extracts specific errors related to HTML elements and outputs information about the violated rules, error text, and problematic areas of the HTML code. This method is suitable for debugging and pinpointing places where accessibility is violated.

 1// Prepare a path to a source HTML file
 2String documentPath = "check-color.html";
 3
 4// Initialize a webAccessibility container
 5WebAccessibility webAccessibility = new WebAccessibility();
 6
 7// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
 8Guideline guideline = webAccessibility.getRules()
 9        .getPrinciple("1").getGuideline("1.4");
10
11// Get criterion by code, for example 1.4.3
12Criterion criterion = guideline.getCriterion("1.4.3");
13
14// Create an accessibility validator, pass the found guideline
15// as parameters and specify the full validation settings
16AccessibilityValidator validator = webAccessibility.createValidator(
17        criterion,
18        ValidationBuilder.getAll()
19);
20
21final HTMLDocument document = new HTMLDocument(documentPath);
22ValidationResult validationResult = validator.validate(document);
23if (!validationResult.getSuccess()) {
24    // Get all result details
25    for (RuleValidationResult ruleResult : validationResult.getDetails()) {
26        // If the result of the rule is unsuccessful
27        if (!ruleResult.getSuccess()) {
28            // Get errors list
29            for (ITechniqueResult result : ruleResult.getErrors()) {
30                // Check the type of the erroneous element, in this case
31                // we have an error in the html element rule
32                if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
33                    // Element of file with error
34                    HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
35
36                    System.out.println(String.format("Error in rule %s : %s",
37                            result.getRule().getCode(), result.getError().getErrorMessage()));
38
39                    System.out.println(String.format("CSS Rule: %s",
40                            rule.getOuterHTML()));
41                }
42}}}}
  1. Use the WebAccessibility() constructor to create an instance of WebAccessibility to access principles and guidelines defined in WCAG.
  2. Specify a guideline (Guideline 1.4) to focus on a specific aspect of web accessibility. Call the getPrinciple() method of the AccessibilityRules class and getGuideline() method of the Principle class to get required principle by code from WCAG.
  3. Use the getCriterion() method of the Guideline class to obtain a specific criterion with the code “1.4.3” from a previously selected guideline. The criterion variable now holds the specific criterion “1.4.3,” and you can use it when creating a validator to check your web content against this particular criterion.
  4. Call the createValidator() method to create a validator object and pass the criterion and ValidationBuilder.getAll() to it as parameters.
    • criterion – is the specific accessibility criterion that represents the specific rule or requirement you want to validate against.
    • ValidationBuilder.getAll() – is the parameter that means you want to check for all aspects covered by the criterion.
  5. Load an HTML document using one of the HTMLDocument() constructors.
  6. Use the validate(document) method to check the HTML content against the selected criterion. The result is stored in the validationResult variable.
  7. Check whether the validation was successful. If the validation results indicate any errors, print output information about the error, including the error message and the rule itself.

When validation fails, the output might look like this:

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>

What steps can you take to guarantee color contrast accessibility?

  1. Make sure the text stands out enough from the background to be easy to read. The Web Content Accessibility Guidelines (WCAG) suggest a minimum contrast ratio of 4.5:1 for regular text and 3:1 for larger text (usually 18-point or 14-point bold). As font size and stroke width increase, readability improves even with lower contrast. Therefore, the contrast requirements for larger text are lower.
  2. Avoid text images and use actual text wherever possible.
  3. Provide descriptive alternative text for images and icons to convey their importance to screen reader users, especially when color variations are employed.
  4. Choose color combinations that suit users with different types of color blindness.
  5. Make sure that the placeholders in forms also have acceptable color contrast.
  6. Use online tools to check contrast and evaluate and confirm the contrast ratios in your website designs.

References

See Also

  • For instructions on checking web content is compatible with screen readers, you will find in the article Screen Reader Accessibility. You will learn how to check alt text and other key elements.
  • If you want to learn how to view validation results and identify web accessibility issues, see the Validation Results article.
  • In the article Web Accessibility Check – Errors and Warnings, you will learn how to programmatically in Java collect error and warning information while checking a website’s accessibility.

Use the free online Color Contrast Checker to check the contrast ratios in your web designs. This tool provides feedback on whether your color choices meet accessibility standards.

Text “Banner for free online application – Color Contrast Checker”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.