:focus

The :focus selector targets elements that currently have keyboard focus. This means that the user has interacted with the element using the keyboard (e.g., by pressing the Tab key or using arrow keys to navigate).

Syntax

element:focus {
  /* Styles to apply when the element has focus */
}

Replace element with the specific element you want to style when it has focus (e.g., input, button, textarea, a, etc.).

Common Use Cases

  • Highlighting Focused Elements
input:focus,
button:focus,
textarea:focus {
  outline: 2px solid blue;
}
  • Changing Cursor
a:focus {
  cursor: pointer;
}
  • Modifying Appearance
select:focus {
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
  • Customizing Keyboard Navigation
input:focus {
  border-color: #007bff;
}

Best Practices

  • Be Mindful of Accessibility: Ensure that your :focus styles are visually distinct from other elements to aid users with disabilities.
  • Consider Keyboard Navigation: Design your styles to provide clear feedback to users navigating with the keyboard.
  • Test Thoroughly: Verify that your :focus styles work as expected across different browsers and devices.
  • Use a CSS Reset or Normalize: To ensure consistent styling across different browsers, consider using a CSS reset or normalize (like Normalize.css) that resets default styles.

Additional Considerations

  • :focus-within: For styling nested elements when the parent has focus, use the :focus-within selector.
  • Keyboard Accessibility: Prioritize keyboard navigation and ensure that your website is fully accessible to users who rely on the keyboard.