С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:
- 1.4.1 Use of Color – Level А
- 1.4.3 Contrast (Minimum) – Level АА
- 1.4.6 Contrast (Enhanced) – Level ААA
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.
- Successfully complying with the condition for Level AA of WCAG 2.0 requires the visual presentation of text with a contrast ratio of at least 4.5:1 for normal text and at least 3:1 for large-scale text.
- For the improved success criterion level AAA, these coefficients are 7:1 for normal text and 4.5:1 for large text or bold text, respectively.
Below you can see an example of proper contrast between font and background and an example of poor contrast:
Let’s write the HTML code for this example to check-color.html
file and check color contrast using Aspose.HTML for .NET 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: #045DE2;
16 font-size: 16px;
17 }
18 .good {
19 background-color: #f0f6ff;
20 font-size: 18px;
21 }
22 </style>
23 </head>
24 <body>
25 <div class="good">Good contrast</div>
26 <div class="bad">Bad contrast</div>
27 </body>
28</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:
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "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"
8var guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
9
10// Get criterion by code, for example 1.4.3
11var criterion143 = guideline.GetCriterion("1.4.3");
12
13// Get criterion by code, for example 1.4.6
14var criterion146 = guideline.GetCriterion("1.4.6");
15
16// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
17var validator = webAccessibility.CreateValidator(new IRule[] { criterion143, criterion146 }, ValidationBuilder.All);
18
19using (var document = new HTMLDocument(documentPath))
20{
21 var validationResult = validator.Validate(document);
22 if (!validationResult.Success)
23 {
24
25 Console.WriteLine(validationResult.SaveToString());
26
27 }
28}
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:
- Create an instance of the WebAccessibility class.
- 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.
- 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. - Call the
CreateValidator() method to create a validator object and pass the
criterion
andValidationBuilder.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.
- Load an HTML document using one of the HTMLDocument() constructors.
- Use the
Validate(
document
) method to check the HTML content against the selected criterion. The result is stored in thevalidationResult
variable. - 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.
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "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"
8var guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
9
10// Get criterion by code, for example 1.4.3
11var criterion = guideline.GetCriterion("1.4.3");
12
13// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
14var validator = webAccessibility.CreateValidator(criterion, ValidationBuilder.All);
15
16using (var document = new HTMLDocument(documentPath))
17{
18 var validationResult = validator.Validate(document);
19 if (!validationResult.Success)
20 {
21 // Get all result details
22 foreach (var ruleResult in validationResult.Details)
23 {
24 // If the result of the rule is unsuccessful
25 if (!ruleResult.Success)
26 {
27 // Get errors list
28 foreach (var result in ruleResult.Errors)
29 {
30 // Check the type of the erroneous element, in this case we have an error in the html element rule
31 if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
32 {
33 // Element of file with error
34 var rule = (HTMLElement)result.Error.Target.Item;
35
36 Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
37 Console.WriteLine("CSS Rule: {0}", rule.OuterHTML);
38 }
39 }
40 }
41 }
42 }
43}
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?
- 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.
- Avoid text images and use text wherever possible.
- Provide descriptive alternative text for images and icons to convey their meaning to screen reader users when color distinctions are used.
- 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.
- 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.
- Ensure that the form’s placeholders also have acceptable color contrast.
- Use online contrast-checking tools to evaluate and verify the contrast ratios in your web designs.
References
- G17: Ensuring that a contrast ratio of at least 7:1 exists between text (and images of text) and background behind the text
- G18: Ensuring that a contrast ratio of at least 4.5:1 exists between text (and images of text) and background behind the texts
- G145: Ensuring that a contrast ratio of at least 3:1 exists between text (and images of text) and background behind the text
- G183: Using a contrast ratio of 3:1 with surrounding text and providing additional visual cues on hover for links or controls where color alone is used to identify them
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.