Documents v0.9.0 · previews run the real runtime · experimental features are marked exp

Focus & blur

Request focus and react when an element loses it.

focus::blurexperimental
Live previewreal runtime

Press Search: the field appears and receives focus. Type, then press Tab or click elsewhere: the field nudges once. Press Search again to hide it.

How it works

  • focus:line 11Moves focus to the matched element when its value goes from false to true because of a user action. In 0.9 this declaration is the focus request: focus: when(--open).
  • :blurline 14Matches an element from a genuine focus loss until it is focused again. Unlike :not(:focus), it never matches on page load.

Two focus behaviors. focus: when(--open) moves focus to the field when the user opens it, and :blur matches the field after it loses focus, here to play a short animation.

Native CSS alternative

:focus, :focus-visible and :focus-within style focus natively and stay the right tool for focus styling; :blur is only for reacting to the moment focus leaves. Moving focus has no CSS equivalent (autofocus works only on load).

Limitations

  • Focus requests need a focusable element: the field here is a native input.
  • Not verified with screen readers.
  • The nudge respects reduced-motion settings only if your stylesheet does; the site previews disable animations under prefers-reduced-motion.

Implementation

2 files · 14 lines
style.cssreactive
/* ---- Reactive CSS -------------------------------------------------------------------------- */.focusing { --open: state(false); }.focusing .open:on(click) { --open: toggle(); }.focusing .open { --attr-aria-expanded: var(--open); }.focusing .field { display: none; }.focusing:when(--open) .field { display: block; }/* A focus request: when --open becomes true, the field takes focus. */.focusing .field { focus: when(--open); }/* From a real focus loss until the field is focused again. */.focusing .field:blur { animation: nudge 250ms; }
state()Function · hover any red tokenMakes each matching element the owner of an independent state with an initial value.Reference →

Source: site/src/catalog/api/focus-blur/. style.css from its Reactive CSS divider; the layout above it and the shared api.css run but are not shown.

Related

Mouse tracker

A dot that follows the pointer inside an area, moved with a transform.

mouse()

Element size

A card reads its own measured width, and its text follows.

experimentalelement():on()

Conditional state

One stored state with three values, and styles chosen from it.

cycle()when():when()