CodeBlanks Logo Icon CodeBlanks

Focus-visible

CSS course · Advanced · Lesson 32/52

Learn accessible focus styles with :focus-visible.

What is :focus-visible?

In CSS the :focus pseudo-class fires whenever an element is focused, both on mouse click and keyboard arrival. :focus-visible fires only when focus arrives through the keyboard or another assistive technology; on mouse click it usually stays hidden.

This was designed to spare mouse users from ugly focus rings. Keyboard users still see a clear focus outline, so accessibility is preserved.

The outline: none trap

Some designs remove the default focus ring with outline: none. This is a disaster for keyboard users: they cannot see where focus is. The fix is not to remove the default but to give it a clear, contrasted ring through :focus-visible.

Example: :focus-visible { outline: 3px solid #ffba00; outline-offset: 2px; }. The ring is thick, contrasted and sits slightly outside the element; users with low vision can still spot it.

Exercise Define a ring for a:focus-visible

Write a declaration block for the a:focus-visible selector. Include the outline: 3px solid #ffba00 and outline-offset: 2px declarations.

Show example solution
/* define the focus ring */
a:focus-visible {
  outline: 3px solid #ffba00;
  outline-offset: 2px;
}

Test yourself

  1. When does :focus-visible behave differently from :focus?

    • Never, they are the same
    • Visible on keyboard focus, usually hidden on mouse click
    • Visible only on mouse click, not on keyboard
    • Visible only on touch screens
    Show answer

    Visible on keyboard focus, usually hidden on mouse click — Correct. :focus-visible appears on keyboard focus; on mouse click it usually stays hidden.

  2. Write the focus ring declaration

    a:focus-visible {
      ____;
      outline-offset: 2px;
    }
    Show answer
    a:focus-visible {
      outline: 3px solid #ffba00;
      outline-offset: 2px;
    }
  3. Match the focus pseudo-classes

    :focus
    Any focus kind
    :focus-visible
    Keyboard focus only
    :focus-within
    Focus on self or child
    outline: none
    Remove focus ring

All lessons in Advanced