Pseudo-Classes/Elements

CSS :focus

Styling Focused Elements

CSS :focus styles focused elements, with :focus-visible for accessibility.

Introduction to :focus Pseudo-Class

The :focus pseudo-class in CSS is used to apply styles to elements that have received focus. Focus is a state where an element is active and ready to receive input from the user, such as when a user clicks on a text input or navigates to a link using the keyboard. This is crucial for ensuring that users can easily identify which element is currently active, enhancing the user experience.

Basic Usage of :focus

The :focus pseudo-class can be applied to any focusable element, such as links, input fields, buttons, and more. When an element receives focus, the styles defined in the :focus rule are applied.

In this example, when an input field receives focus, its border color changes to blue, and the default outline is removed.

Improving Accessibility with :focus-visible

While :focus is essential for styling focused elements, :focus-visible is a more refined pseudo-class that specifically targets elements that should have a focus indication, especially when navigated to via the keyboard. This improves accessibility by allowing mouse users to avoid unnecessary focus styles while ensuring keyboard users see them.

Here, the button will only have an orange outline when it is focused via keyboard navigation, not when clicked with a mouse.

Combining :focus and :hover

It's common to combine :focus with :hover to ensure consistent styling behavior when users interact with elements using different input methods. This enhances usability by providing visual feedback for both hover and focus states.

In this example, links will change to a red color and be underlined when hovered over or focused, making them more noticeable.

Practical Considerations

When designing your website, consider the following best practices for using :focus:

  • Ensure focus styles are clear and noticeable, but not distracting.
  • Test focus styles on different devices and browsers to ensure consistency.
  • Combine :focus with other pseudo-classes like :hover for a seamless user experience.
Previous
:hover