Technique C15:Using CSS to change the presentation of a user interface component when it receives focus
About this Technique
This technique relates to:
- 1.4.1: Use of Color (Advisory)
- 2.4.7: Focus Visible (Sufficient)
This technique applies to CSS, HTML.
Description
The objective of this technique is to demonstrate how visual appearance may be enhanced via style sheets to provide visual feedback when an interactive element has focus or when a user hovers over it using a pointing device. Highlighting the element that has focus or is hovered over can provide information such as the fact that the element is interactive or the scope of the interactive element.
Providing visual feedback may be possible through more than one mode. Usually, it is attained through using a mouse to hover over the element or a keyboard to tab to the element.
Examples
Example 1: Link elements
In this example, mouse and keyboard focus indicators have been applied to the link elements. CSS has been used to apply a background color when the link elements receive focus.
Here is the content to be displayed:
<nav id="main-nav">
<ul>
<li>Home</li>
<li><a href="/services">Services</a></li>
<li><a href="/projects">Projects</a></li>
<li><a href="/demos">Demos</a></li>
<li><a href="/about-us">About us</a></li>
<li><a href="/contact-us">Contact us</a></li>
<li><a href="/links">Links</a></li>
</ul>
<nav>
Here is the CSS that changes the background color for the above elements when they receive mouse or keyboard focus:
#main-nav a:hover, #main-nav a:active, #main-nav a:focus-visible {
background-color: #DCFFFF;
color:#000066;
}
Example 2: Highlighting elements that receive focus
In this example, the :focus pseudo-class is used to change the style applied to input fields when they receive focus by changing the background color.
<!doctype html>
<html lang="en">
<head>
<style>
input[type=text]:focus-visible {
outline:2px solid #0054AE;
outline-offset:2px;
}
input[type=checkbox]:focus + label, input[type=radio]:focus + label {
background-color:#1E2EB8;
color:#FFF;
}
</style>
</head>
<body>
<form>
<div>
<label for="fname">Name: </label>
<input autocomplete="name" type="text" name="fname" id="fname">
</div>
<div>
<input type="radio" name="sex" value="male" id="sm">
<label for="sm">Male</label>
</div>
<div>
<input type="radio" name="sex" value="female" id="sf">
<label for="sf">Female</label>
</div>
</form>
</body>
</html>
Working example of this code: Example of highlighting elements that receive focus.
Related Resources
No endorsement implied.
Tests
Procedure
For each element able to attain focus:
- Using a keyboard, tab to the component.
- Check that the focus indicator changes color.
- Check that the focus indicator is removed when the component loses focus.
Expected Results
- Checks #2 and #3 true.