CSS Reference ยท Pseudo-classes
The :focus pseudo-class
Reference for the CSS :focus pseudo-class: style the element that has input focus, with syntax, examples, accessibility advice, usage notes and browser support.
The :focus pseudo-class matches the element that currently has focus: the one that will receive keystrokes. Form fields, buttons, links and any element with a tabindex can be focused, by clicking, tapping, or moving with the Tab key.
Focus styling is an accessibility feature. People who navigate with a keyboard rely on it to know where they are on the page.
input:focus { border-color: #2563eb; }
Try it
Syntax
:focus { /* declarations */ }
:focus has no arguments and a specificity of (0,1,0). Only one element in a document (per focus context) matches at a time, plus, in practice, only while the window is active.
Syntax and arguments
| Part | Description |
|---|---|
:focus |
Matches the element that currently has focus. |
| No arguments | The pseudo-class is not functional. |
| Combining | a:focus, .card button:focus; to style an ancestor of the focused element use :focus-within. |
Usage notes
- Never remove the outline without a replacement.
outline: noneleaves keyboard users lost. If you replace the default ring, make the new indicator clearly visible against its background. - Mouse clicks also match. Clicking a button focuses it in most browsers, so a strong
:focusstyle appears on every click. Many designs use:focus-visiblefor the ring and keep:focusminimal. - Not every element is focusable. A plain
<div>never matches unless it hastabindex. Usetabindex="0"only for custom controls that really need keyboard access. - Safari and buttons. Some browsers do not focus buttons on click, so do not rely on
:focusappearing after a mouse press. - Contrast. The indicator should stand out from both the element and its surroundings; a thin pale line is easy to miss.
Browser support
Supported in every browser.
Related
:focus-visibleโ focus that should show an indicator:focus-withinโ a container of the focused element:hoverโ pointer over the element- Lessons: Pseudo-classes, Outline, Accessibility