Using CSS to change the presentation of a user interface component when it receives focus

Important Information about Techniques

See Understanding Techniques for WCAG Success Criteria for important information about the usage of these informative techniques and how they relate to the normative WCAG 2.1 success criteria. The Applicability section explains the scope of the technique, and the presence of techniques for a specific technology does not imply that the technology can be used in all situations to create content that meets WCAG 2.1.

Applicability

CSS, HTML and XHTML

This technique relates to:

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

<html>
  <head>
    <style type="text/css">
      input.text:focus {
        background-color: #7FFF00; 
        color: #000;
      }
      input[type=checkbox]:focus + label, input[type=radio]:focus + label {
        background-color: #FF6; 
        color: #000; 
      }
    </style>
  </head>
  <body>
    <form method="post" action="form.php">
      <p><label for="fname">Name: </label>
        <input class="text" type="text" name="fname" id="fname" />
      </p>
      <p>
        <input type="radio" name="sex" value="male" id="sm" /> <label for="sm">Male</label><br />
        <input type="radio" name="sex" value="female" id="sf" /> <label for="sf">Female</label>
      <p>
    </form>
  </body>
</html>

            

Working example of this code: Example of highlighting elements that receive focus.

Resources

Resources are for information purposes only, no endorsement implied.

Tests

Procedure

For each element able to attain focus:

  1. Using a mouse, hover over the element.
  2. Check that the background or border changes color.
  3. Move the mouse away from the object before attempting keyboard focus.
  4. Using a keyboard, tab to the element.
  5. Check that the background or border changes color.
  6. Check that the background or border changes in color are removed when the element loses focus.

Expected Results

  • Checks #2, #5 and #6 are true.