CSS - Focus

-

Applying Focus Styles

When an element receives focus, browsers apply default focus styles to show the focused state. These default styles vary between browsers but usually involve a dotted or solid outline around the element. While the default focus styles provide a basic visual cue, they may not always match your website's design. CSS lets you customize the focus styles to fit your website's look and improve the user experience.

One common way to customize focus styles is by using the outline property. The outline property lets you set the style, color, and width of the outline around an element when it receives focus.

Outline Property Example

:focus {
  outline: 2px solid blue;
}

Another option for styling focused elements is the box-shadow property. By applying a box shadow, you can create a glowing effect around the element when it receives focus.

Box-Shadow Property Example

:focus {
  box-shadow: 0 0 5px rgba(0, 0, 255, 0.8);
}

In addition to the outline and box-shadow properties, you can also use the background and border properties to further customize the look of focused elements. For instance, you can change the background color or add a border to create a distinct visual style:

Background and Border Properties Example

:focus {
  background-color: lightblue;
  border: 2px solid blue;
}

When applying focus styles, it's important to keep best practices in mind. One key point is making sure there is enough contrast between the focused element and its surroundings. This helps users, especially those with visual impairments, easily see which element has focus. The Web Content Accessibility Guidelines (WCAG) recommend a minimum contrast ratio of 4.5:1 for focus indicators.

Another best practice is to keep consistent styling across different types of elements. This means applying similar focus styles to interactive elements like buttons, links, and form controls. Consistency in focus styles helps users understand that these elements are focusable and interactive, no matter what type they are.

Focus Pseudo-classes

CSS has pseudo-classes made to target elements based on their focus state. These pseudo-classes let you style elements when they get focus or contain focused elements.

The :focus pseudo-class selects an element when it has focus, either through keyboard or clicking. The syntax for :focus is:

Example: Focus Pseudo-class

.element:focus {
  /* Styles used when the element has focus */
}

You can use :focus with other selectors to target specific elements. For example, you can style only input elements of a specific class:

Example: Focus with Specific Class

input.text-field:focus {
  /* Styles used when an input element with the class 'text-field' has focus */
}

The :focus-within pseudo-class selects an element if it has focus or any of its child elements have focus. This helps when you want to style a parent element based on the focus state of its children.

Example: Focus Within Pseudo-class

.container:focus-within {
  /* Styles used when the container or any of its children has focus */
}

A common use for :focus-within is to highlight a form when any of its input elements has focus. This helps users know which form they are using.

The :focus-visible pseudo-class is like :focus, but it only styles when an element has focus and the focus is visible to the user. This pseudo-class helps give focus styles for keyboard use while avoiding the same styles when an element is clicked. The syntax for :focus-visible is:

Example: Focus Visible Pseudo-class

.element:focus-visible {
  /* Styles used when the element has focus and the focus is visible */
}

The main difference between :focus and :focus-visible is that :focus-visible only styles when the focus is visible, usually when using the keyboard. This lets you have different focus styles for keyboard and mouse use, making the user experience better.

Managing Focus with JavaScript

While CSS lets you style elements when they get focus, sometimes you need more control over focus behavior. This is where JavaScript helps. With JavaScript, you can manage focus, direct it to specific elements, trap it within containers, and create accessible interactions.

One way to control focus using JavaScript is through the Element.focus() method. This method lets you set focus on a specific element with code.

Example: Using Element.focus() Method

const element = document.getElementById('myElement');
element.focus();

Another way to manage focus is by setting the tabindex attribute on elements. The tabindex attribute decides the order in which elements get focus when using the Tab key for navigation. By default, only interactive elements like buttons, links, and form controls are included in the tab order. However, you can use the tabindex attribute to include or exclude elements from the tab order.

Example: Setting tabindex Attribute

<div tabindex="0">This element can receive focus.</div>
<div tabindex="-1">This element can receive focus programmatically, but not through tab navigation.</div>

Managing focus is important when making accessible modal dialogs or adding keyboard navigation within a container. When a modal dialog opens, it's important to trap the focus within the modal to prevent users from accidentally interacting with the underlying content. This can be done by moving the focus to the first focusable element within the modal and then trapping the focus within the modal using JavaScript.

Example: Trapping Focus within a Modal

const modal = document.getElementById('modal');
const focusableElements = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const firstFocusableElement = focusableElements[0];
const lastFocusableElement = focusableElements[focusableElements.length - 1];

// Move focus to the first focusable element in the modal
firstFocusableElement.focus();

// Trap focus within the modal
modal.addEventListener('keydown', function(e) {
  if (e.key === 'Tab') {
    if (e.shiftKey) {
      // If Shift + Tab is pressed
      if (document.activeElement === firstFocusableElement) {
        e.preventDefault();
        lastFocusableElement.focus();
      }
    } else {
      // If Tab is pressed
      if (document.activeElement === lastFocusableElement) {
        e.preventDefault();
        firstFocusableElement.focus();
      }
    }
  }
});

Adding proper focus management is important for making accessible and keyboard-friendly interfaces. By using JavaScript to control focus, you can guide users through your application, provide clear focus indicators, and make sure that all interactive elements are reachable and usable with the keyboard.

Accessible Focus Management

Managing focus is a key part of creating accessible websites. Proper focus management helps users move through and interact with your website using the keyboard alone, without relying on a mouse or other pointing device. This is particularly important for users with visual impairments who use screen readers or users with motor disabilities who may have trouble using a mouse.

One of the main techniques for improving focus accessibility is to provide clear and visible focus indicators. When an element receives focus, it should have a distinct visual style that sets it apart from other elements on the page. This can be achieved using CSS focus styles, such as changing the background color, adding an outline, or applying a box shadow to the focused element. The focus indicator should have enough contrast against the background to make sure it is easy to see.

Another important consideration is making sure the focus order is logical. The focus order should follow the natural reading order of the page and match the visual layout. This means that when users move through the page using the Tab key, the focus should move in a predictable and intuitive way. You can control the focus order by properly structuring your HTML markup and using the tabindex attribute when necessary.

In addition to visual focus indicators, it's also important to announce focus changes to users of assistive technologies, such as screen readers. This can be done using ARIA (Accessible Rich Internet Applications) attributes.

Example: Using the aria-live attribute

<div aria-live="polite">Live Region</div>

This attribute helps announce dynamic changes in the page content.

You can also use the aria-describedby attribute to provide additional context for focused elements.

Example: Using the aria-describedby attribute

<input id="name" aria-describedby="name-desc">
<div id="name-desc">Enter your full name.</div>

This example provides extra information about the input field.

To make sure your website has good focus accessibility, testing is essential.

Example: Using only the keyboard for testing

Move through the website using only the keyboard, typically using the Tab key to move between focusable elements. Check for visible focus indicators, logical focus order, and accessibility of all important elements.

In addition to manual testing, there are also automated testing tools and techniques available. These tools can help identify focus-related accessibility problems and provide guidance on how to fix them. Some popular accessibility testing tools include:

Tool Description
aXe A browser extension and JavaScript library that tests web pages for accessibility issues, including focus-related problems.
WAVE A web accessibility evaluation tool that provides visual feedback about the accessibility of your web pages, including focus indicators and keyboard navigation.
Lighthouse An open-source, automated tool for improving the quality of web pages, including accessibility. It checks for focus-related issues and provides suggestions for improvement.