10 August 2024

In CSS, you can differentiate between keyboard and mouse focus using different pseudo-classes and selectors. :focus-visible - This pseudo-class targets elements that should be visibly focused, typically those navigated to using the keyboard. :focus:not(:focus-visible) - This targets elements that are focused but not visibly focused, such as when the focus is applied via the mouse. By setting the outline to none, you can hide the default focus ring that appears when using the mouse.

Source code viewer
  1. /* Style for elements focused via keyboard */
  2. :focus-visible {
  3. outline: 2px solid blue; /* Keyboard focus */
  4. }
  5.  
  6. /* Style for elements focused via mouse */
  7. :focus:not(:focus-visible) {
  8. outline: none; /* Mouse focus */
  9. }
Programming Language: CSS