CSS focus-visible Ring That Survives Themes

Style a high-contrast keyboard focus ring with :focus-visible, transparent base outlines, a halo, and forced-colors support.

CssSecurity Boundaries

Code

csssnippet
38 lines
:root {
  --focus-ring: #4f46e5;
  --focus-halo: rgb(79 70 229 / 25%);
}

/* Reserve the ring in the base state so layout never shifts on focus.
   A transparent outline also becomes visible in Windows High Contrast. */
:where(a, button, input, select, textarea, summary, [tabindex]:not([tabindex="-1"])):focus {
  outline: 3px solid transparent;
  outline-offset: 3px;
}

:where(a, button, input, select, textarea, summary, [tabindex]:not([tabindex="-1"])):focus-visible {
  outline: 3px solid var(--focus-ring);
  outline-offset: 3px;
  box-shadow: 0 0 0 6px var(--focus-halo);
}

@media (forced-colors: active) {
  :focus-visible {
    outline: 3px solid Highlight;
    box-shadow: none;
  }
}

@media (prefers-reduced-motion: no-preference) {
  :where(a, button, input, select, textarea, summary):focus-visible {
    transition: outline-offset 120ms ease-out;
  }
}

/* Browsers without :focus-visible keep a visible ring for all focus. */
@supports not selector(:focus-visible) {
  :where(a, button, input, select, textarea, summary, [tabindex]:not([tabindex="-1"])):focus {
    outline: 3px solid var(--focus-ring);
    box-shadow: 0 0 0 6px var(--focus-halo);
  }
}

How it works

prefers-reduced-motion hands you the user’s animation preference so heavy motion can be skipped.

Values that repeat across rules live in custom properties (--focus-ring, --focus-halo, --focus-ring, --focus-halo, --focus-ring), so a theme change is one edit instead of a hunt through every rule.

2 media queries adjust the layout where the current arrangement stops fitting.

Motion goes through transition, keeping animation on compositor-friendly properties.

State-dependent styling attaches through :focus, :focus-visible rather than class toggling from script.

The rules target :root, :focus-visible — each selector names the element it restyles, in source order.

What to watch for in this file

  • Prefer animating only the properties this snippet declares (via transition); animating layout properties forces reflow every frame.

Interactive Tools for This Topic

FAQ

Which elements does this stylesheet target?
The rules bind to `:root`, `:focus-visible`; when two rules tie in specificity, the one written later in the file wins.