CodeBlanks Logo Icon CodeBlanks

Focus states

CSS course · Intermediate · Lesson 78/98

Learn focus styles with :focus and :focus-visible.

The :focus pseudo-class

When a user clicks an input or reaches it with Tab, that field is focused. In CSS, the :focus pseudo-class catches that moment.

By changing the look of the focused field, you show the user where they are. A common setting: outline: 2px solid #2563eb;. It adds a clear frame instead of changing the browser's default ring.

The :focus-visible difference

Sometimes a focus ring is unwanted on mouse click; it should only show when navigating with the keyboard. The :focus-visible pseudo-class separates the two.

The browser applies :focus-visible styles only for keyboard focus; :focus styles for mouse clicks. Mouse users stay undisturbed; keyboard users still see the ring every time.

Accessible focus

The focus ring is not just decoration; it is an accessibility requirement. Keyboard users, screen-reader users and people with low vision rely on it.

That is why outline: none is dangerous. If you remove it, you must add a visible replacement: a bold border, an underline, a clear background. Otherwise the form locks out keyboard users.

Exercise Write two focus rings

Write two declaration blocks. For input:focus: outline: 2px solid #2563eb;. For input:focus-visible: outline: 3px solid #2563eb;.

Show example solution
open two selectors; put each outline declaration inside.
Example solution:
input:focus {
  outline: 2px solid #2563eb;
}
input:focus-visible {
  outline: 3px solid #2563eb;
}

Test yourself

  1. When does :focus-visible apply?

    • Only when focused with the keyboard
    • Only when clicked with the mouse
    • On every focus, unconditionally
    • Only when the form is submitted
    Show answer

    Only when focused with the keyboard — Correct! :focus-visible separates keyboard focus; mouse users stay calm.

  2. Give input:focus a ring

    input:focus {
      outline: ____;
    }
    Show answer
    input:focus {
      outline: 2px solid #2563eb;
    }
  3. Match focus concepts

    :focus
    every focus
    :focus-visible
    keyboard focus
    outline
    focus ring
    accessibility
    keyboard user

All lessons in Intermediate