Сolor Сontrast Accessibility – Check Color Contrast in C#

If you want to check the website for compliance with WCAG guidelines programmatically in C#, the Aspose.HTML for .NET provides the Aspose.Html.Accessibility namespace, which is for all Web Accessibility related manipulations and checks. Find out if your website is WCAG  compliant!

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 .NET API and make your web content easy to read for all users.

Accessible Color Contrast

In color theory, contrasting colors are colors from opposite segments of the color wheel. Colors directly opposite each other on the basic color wheel provide maximum contrast. Accessible color contrast is essential to ensure web content is readable and usable by people with visual or color vision impairments. Accessibility principles focus on contrasting text and background colors to make content legible and distinguishable. Choosing the proper contrast and color is vital to creating an inclusive and user-friendly web experience for everyone.

The test criteria for color contrast are contained in the guideline 1.4 – Distinguishable, there are such test criteria:

Regarding color contrast, the WCAG determines two levels of contrast ratios depending on the level of success criteria: AA (minimum contrast) and AAA (enhanced contrast). Criteria checks the contrast ratio between text and its background. Contrast ratios can range from 1 to 21.

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

Good contrast
Bad contrast

Let’s write the HTML code for this example and check color contrast using Aspose.HTML for .NET API.

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

Check Color Contrast – C# 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 all the criteria that relate to checking contrast – find the principle by code and pass it to the accessibility validator:

 1using Aspose.Html;
 2using Aspose.Html.Accessibility;
 3using System.IO;
 4...
 5    // Initialize a webAccessibility container
 6    WebAccessibility webAccessibility = new WebAccessibility();
 7
 8    // Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
 9    var guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
10
11    // Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
12    var validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
13
14    // Initialize an object of the HTMLDocument
15    using (var document = new HTMLDocument(htmlFile))
16    {
17        // Check the document using the Validate() method
18        var validationResult = validator.Validate(document);
19
20        // Checking for success
21        if (!validationResult.Success)
22        {
23            // here is the result handling code
24        }
25    }

Check Color Contrast Against Specific Accessibility Criteria

The following C# code is designed to validate a web page against specific accessibility criteria, and you will receive a report of issues related to those rules. To check a specific criterion, specify it as a parameter for the accessibility validator:

  1. Create an instance of the WebAccessibility class.
  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.All to it as parameters.
    • criterion – is the specific accessibility criterion that represents the specific rule or requirement you want to validate against.
    • ValidationBuilder.All – 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.
 1using Aspose.Html;
 2using Aspose.Html.Accessibility;
 3using System.IO;
 4...
 5    // Initialize a webAccessibility container
 6    WebAccessibility webAccessibility = new WebAccessibility();
 7
 8    // Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
 9    var guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
10
11    // Get criterion by code, for example 1.4.3
12    var criterion = guideline.GetCriterion("1.4.3");
13
14    // Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
15    var validator = webAccessibility.CreateValidator(criterion, ValidationBuilder.All);
16
17    using (var document = new HTMLDocument(htmlFile))
18    {
19        var validationResult = validator.Validate(document);
20        if (!validationResult.Success)
21        {
22            // Get all result details
23            foreach (var ruleResult in validationResult.Details)
24            {
25                // If the result of the rule is unsuccessful
26                if (!ruleResult.Success)
27                {
28                    // Get errors list
29                    foreach (var result in ruleResult.Errors)
30                    {
31                        // Check the type of the erroneous element, in this case we have an error in the html element rule
32                        if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
33                        {
34                            // Element of file with error
35                            var rule = (HTMLElement)result.Error.Target.Item;
36
37                            Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
38                            Console.WriteLine("CSS Rule: {0}", rule.OuterHTML);
39                        }
40                    }
41                }
42            }
43        }
44    }

The result of the file check will be a list of results containing one error with type IError. The program will output to the console:

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, and less than 14 points if it is in bold.
2    CSS Rule: <div class="bad">Bad contrast</div>

What can you do to ensure color contrast accessibility?

  1. Make sure the text has enough contrast with the background to be readable. The Web Content Accessibility Guidelines (WCAG) recommend a minimum contrast ratio of 4.5:1 for standard text and 3:1 for large text (typically 18-point or 14-point bold). The larger the font and wider the stroke, the more legible it will be with less contrast. Consequently, the contrast requirements for larger fonts are lower.
  2. Avoid text images and use text wherever possible.
  3. Provide descriptive alternative text for images and icons to convey their meaning to screen reader users when color distinctions are used.
  4. Choose color combinations that suit users with different types of color blindness. Don’t rely solely on color to convey information; use text labels, patterns, or icons.
  5. Familiarize yourself with available design patterns and best practices, such as using high-contrast color schemes and ensuring important content is not hidden or obscured by color choices.
  6. Ensure that the form’s placeholders also have acceptable color contrast.
  7. Use online contrast-checking tools to evaluate and verify the contrast ratios in your web designs.

References

Use the 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.