Codectionary / Developer documentation / CSS

:focus-visible and :focus-within

:focus-visible applies only when the browser determines focus should be visibly indicated - typically keyboard navigation, not a mouse click - solving the old complaint of unwanted focus rings on click. :focus-within applies to a parent element when any descendant inside it has focus, useful for highlighting an entire form group when one of its fields is active.

Syntax

:focus-visible { }
:focus-within { }

Examples

:focus-visible - Smarter Focus Rings

Showing a focus ring for keyboard users without cluttering mouse interactions.

.button:focus {
  outline: none; /* remove the default outline for ALL focus, including mouse clicks */
}

.button:focus-visible {
  outline: 2px solid #3b82f6; /* but restore it specifically for keyboard focus */
  outline-offset: 2px;
}

:focus-within - Highlighting a Parent Group

Styling an entire form field group when any of its inputs are focused.

.field-group {
  border: 1px solid #d1d5db;
  transition: border-color 0.15s ease;
}

.field-group:focus-within {
  border-color: #3b82f6; /* highlights the whole group, not just the individual input */
}

Parameters and values

  • :focus-visible (pseudo-class): Focus styling that only appears for keyboard/non-pointer interaction
  • :focus-within (pseudo-class): Matches a parent when any descendant has focus

Best practices

  • Use :focus-visible instead of :focus for custom focus ring styling - it correctly avoids showing rings on simple mouse clicks while preserving them for keyboard users
  • Use :focus-within to visually group and highlight a fieldset or custom dropdown component when any part of it is actively focused
  • Never combine outline: none with :focus alone and no :focus-visible fallback - that removes focus indication entirely, a serious accessibility regression
  • Test focus behavior with actual keyboard (Tab key) navigation, not just mouse clicks, to confirm the intended pseudo-class is doing what you expect

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation