Screen Reader Accessibility – C# Examples

Screen Reader as an Assistive Technology

Screen reader accessibility is a crucial aspect of web accessibility that focuses on making digital content, particularly websites and applications, accessible to individuals who are blind or visually impaired.

A screen reader is an assistive technology designed to read online content aloud. It turns the digital text and visual content into speech or Braille, allowing users with visual disabilities to navigate, interact with, and understand digital content. Screen readers are needed not only for blind and visually impaired people but also for users with cognitive impairments, who find it easier to process information by ear.

Screen readers can read any content on a page. For example, text from paragraphs and headings, lists, alternative image descriptions, links, radio buttons, and other interactive elements. Therefore, in order for screen readers to read information that will be accessible and understandable to the user, it is necessary to provide alternative text, as well as informative headings.

Use the following recommendations based on WCAG to ensure your website is accessible to people who rely on screen readers. This is important not only for people with disabilities. It will improve the user experience for everyone and allow your site to rank higher in search engine results.

Alternative text

Screen readers cannot translate an image into words that get read to the user, even if the image only consists of text. For web accessibility, images must have short, descriptive alt text so screen reader users clearly understand the image’s contents and purpose. In addition to the importance of alternative text for people with vision problems, it performs several other essential functions:

Alternative text can be presented on your website in several ways:

Alternative Text for Images – alt attribute in img tag

Ensure all informative <img> elements have short and descriptive, defining alternate text and all decorative <img> elements have empty alt attributes (e.g. alt=""). When writing alt text, remember that its purpose is to relay information to blind users about the image’s contents and purpose so that they get as much information from alt text as a sighted user gets from the image itself. Alt text should give the image’s intent, purpose, and meaning.

In the example below, the content of the image tells the user that the portrait is of a girl and what she looks like:

1<img src="girl_with_perl.png" alt="A European girl is depicted in an exotic dress, oriental turban and with a very large pearl as an earring">
A European girl is depicted in an exotic dress, oriental turban and with a very large pearl as an earring

To ensure your alt text doesn’t get on the nerves of people who use screen readers, use minimal words, be specific, and don’t stuff the alt text with keyword phrases. This is not the place to put keywords. Don’t announce that this is an image. The main task is to describe in words and help blind people understand the purpose of the image on the page.

Alt attribute in Buttons – button alt text

Using the alt attribute in buttons and image buttons is a crucial web accessibility practice. Image buttons use the alt attribute as the label. The alt attribute value must be provided and clear, concise, and representative of the action performed when the user activates the button, not a description of the image itself. This text is read aloud by screen readers, making it possible for individuals who are blind or visually impaired to understand and interact with the button’s functionality.

Check that the <input type="image"> has a non-empty alt attribute.

1<input type="image" src="print.jpg" name="submit" alt="Print">

Use specific and meaningful descriptions. Avoid generic terms like “button” or “image”. If the button performs an action, describe that action. For example, “Submit,” “Search,” or “View Details.” If the button is decorative and doesn’t have a function, use an empty alt attribute (alt="") or remove the alt attribute altogether.

1<button type="submit">
2    <img src="submit-button.png" alt="Submit Form">
3</button>

Alternative Text for content rendered using an <object> element

The <object> element embeds external content, such as images, videos, or interactive applications, into a web page. To make this content accessible to people with disabilities, you should use the alt attribute on the embedded content type.

If the content is an image, use the alt attribute within the <object> element to provide alternative text. The alternative text should describe the content’s purpose or give a meaningful description. For example:

1<object >
2    <img src="aspose.gif" alt="Logo Aspose company" />
3</object> 
4
5<object data="companylogo.gif" type="image/gif">
6    <p>Company name</p>
7</object>

If the content is purely decorative and does not convey meaningful information, consider using an empty alt attribute or omitting it.

<label> elements as associate text labels with form controls

Using <label> elements to associate text labels with form controls is a fundamental practice in web development and an essential aspect of web accessibility. This method enhances usability and ensures that users, including people with disabilities, can effectively understand and interact with forms.

Use the <label> element to associate a form control with a label explicitly. The label is attached to a particular form control using the for attribute. The value of the for attribute must be the same as that of the id attribute of the form control.

1<label for="firstname">First name:</label>
2<input type="text" id="firstname">
3
4<label for="password">Enter password:</label>
5<input type="password" id="password">

The screen reader announces a label when the control receives focus, providing disabled users with context and understanding of the control’s purpose. Labels are significant for various types of form controls, such as text inputs, radio buttons, checkboxes, and dropdowns. Always use labels for these controls to ensure a clear and accessible user experience. Explicitly associated labels are used for all <input> elements except:

title attribute to identify form controls when a <label> element cannot be used

Use the title attribute to provide an accessible name for form controls when the visual design does not include on-screen text that can be associated with the control as a label. User agents, including assistive technologies, may pronounce this title attribute.

Success

Payment card details
1<fieldset><legend>Payment card details</legend>
2<input id="cardnumber" name="cardnumber" title="Enter Card number" type="text" >
3<input id="cvc" name="cvc" title="Enter CVC code" type="text" >
4</fieldset>

Fail

There is no label binding for the input field and the title attribute is also missing:

1<label>Search for:</label>
2<input id="searchTerm" type="text" value="" name="searchTerm">

Alternative text for emojis, emoticons, ASCII art, and leetspeak

Because assistive technologies like screen readers can’t interpret images directly, they rely on alternative text to communicate the meaning of non-text content to users. If an ASCII, emoji, or emoticon image is used, they must also have a textual explanation of what the image is. Because you can’t use an alt attribute on <span>, <div>, etc, and the ARIA recommendation disallows accessible names for generic elements, in order to give emoji accessible names, they are defined as images with the role="img" ARIA property, which then allows you to create an accessible name using this aria-label property.

The attribute role="img" is used to identify the container for a collection of elements that together form a single meaningful image. Alternative text is a word or phrase that is coded in a way that assistive technologies can associate it with a specific non-text object, and conveys the same information as the non-text object.

Success

1<abbr title="sad">:(</abbr>
2<span aria-label="sad" role="img">:(</span>
3<img alt="sad" src="./sad.png">
4
5<div role="img" aria-label="scared face">(ㆆ _ ㆆ)</div>

Fail

1<div role="img">(ㆆ _ ㆆ)</div>

Always aim for a clear and meaningful alternative text that conveys the essence of the emoji, emoticon, ASCII art, or leetspeak while maintaining the intended emotional or expressive tone.

Figure and figcaption

A <figure> element, designed to house <img> and <figcaption>, is self-contained and is typically referenced as a single block from the main flow of the document. The <figure> can be separated from the main flow of the document without affecting its meaning.

The <figure> creates a semantic association with the <figcaption> it contains, which can provide a summary of or additional information about the figure and/or relate it back to the document. However, the <img> still needs alt text, and to avoid redundancy, this information should not be passed through <figcaption>.

1<figure>
2    <img src="./sunset.jpg" alt="Sunset on the sea" />
3    <figcaption>Sunset on the sea</figcaption>
4</figure>

How to Check Alt Text of an Image with Aspose.HTML for .NET

Let’s look at a code snippet related to checking alt text for images and labels. To review your page for alternative text and accessibility criteria, you need to follow these steps:

  1. Use the WebAccessibility() constructor to create an instance of the WebAccessibility class responsible for web accessibility validation.
  2. Use the Rules property of the webAccessibility object that provides access to a collection of web accessibility rules.
  3. Call the CreateValidator() method to create a validator object. You are essentially setting up a validator that will check web content against the specific accessibility guidelines and success criteria associated with the guideline you’ve specified.
  4. Load an HTML document using one of the HTMLDocument() constructors.
  5. Use the Validate(document) method to check the HTML document for accessibility. The result is stored in the validationResult variable.
  6. Check whether the validation was successful. Print the detailed information about errors, including the associated HTML element.

Consider an example of the HTML file alt-tag.html:

 1<html>
 2    <body>
 3        <img src="./resourses/login.png" alt="Login icon">
 4
 5        <label>Enter login:</label>
 6        <!--error: for input missing label with for="login" -->
 7        <input type="text" id="login">
 8
 9        <label for="password">Enter password:</label>
10        <input type="password" id="password">
11    
12        <!--error: for image alt attribute must not be empty -->
13        <img src="./resourses/sign.png" alt="">
14    </body>
15</html>

The following C# code snippet demonstrates the basic steps to create a validator, load an HTML document, and validate it against web accessibility requirements, namely the “1. Perceivable”, “1.1 Text Alternatives” rules:

 1// Prepare a path to a source HTML file
 2string documentPath = Path.Combine(DataDir, "alt-tag.html");
 3
 4// Initialize webAccessibility container
 5var webAccessibility = new WebAccessibility();
 6
 7// Get from the rules list Principle "1. Perceivable" by code "1" and get guideline "1.1 Text Alternatives"
 8var guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.1");
 9
10// Create an accessibility validator - pass the found guideline as parameters and specify the full validation settings
11var validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
12
13// Initialize an HTMLDocument object
14using (var document = new HTMLDocument(documentPath))
15{
16    var validationResult = validator.Validate(document);
17    if (!validationResult.Success)
18    {
19        // Get all the result details 
20        foreach (var ruleResult in validationResult.Details)
21        {
22            // If the result of the rule is unsuccessful           
23            if (!ruleResult.Success)
24            {
25                // Get an errors list 
26                foreach (var result in ruleResult.Errors)
27                {
28                    // Check the type of the erroneous element, in this case, we have an error in the HTML Element
29                    if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
30                    {
31                        var rule = (HTMLElement)result.Error.Target.Item;
32                        Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
33                        Console.WriteLine("HTML Element: {0}", rule.OuterHTML);
34                    }
35                }
36            }
37        }
38    }
39}

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:

1    Error in rule H37 : Img element missing an alt attribute. The value of this attribute is referred to as "alt text".
2    HTML Element: <img src="./resourses/sign.png" alt="">
3    Error in rule H44 : Check that the label element contains for attribute.
4    HTML Element: <label>Enter login:</label>
5    Error in rule H65 : Check that the title attribute identifies the purpose of the control and that it matches the apparent visual purpose.
6    HTML Element: <input type="text" id="login">
7    Error in rule F65 : Absence of an alt attribute or text alternative on img elements, area elements, and input elements of type "image".
8    HTML Element: <img src="./resourses/sign.png" alt="">

References

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.