Skip to content

CSS Tutorial CSS Pseudo-classes

CSS :focus, :focus-visible and :focus-within

Lesson 118 of 182 2 min read By Deepak Paswan Updated Oct 4, 2026

When someone presses Tab, the browser moves focus from one control to the next: links, buttons, form fields. A visible focus indicator tells them where they are. Without it, keyboard users are blind.

:focus

Matches the element that currently has focus, whether it got it by click or by keyboard.

:focus-visible

Matches focus only when the browser thinks a visible ring is useful, which is mostly keyboard focus. A mouse click on a button does not trigger it, but a Tab press does.

index.html
HTML
<style>
  a, button, input { margin: 6px; }
  a:focus-visible, button:focus-visible, input:focus-visible {
    outline: 3px solid #d94a00;
    outline-offset: 3px;
  }
</style>
<a href="#">A link</a>
<button>A button</button>
<input placeholder="A field">

Click into the Result panel, then press Tab to move through the controls and watch the orange ring.

:focus-within

Matches a parent when any of its children has focus. Great for highlighting a whole form row or search box.

index.html
HTML
<style>
  .search { display: flex; border: 2px solid #ccc; border-radius: 8px; padding: 4px; }
  .search:focus-within { border-color: #1a5276; box-shadow: 0 0 0 3px #1a527633; }
  .search input { border: 0; outline: 0; flex: 1; padding: 6px; }
</style>
<div class="search"><input placeholder="Search books…"><button>Go</button></div>

The box lights up when you click into the field. The input’s own outline is removed, but the visible focus is shown on the parent instead. That is acceptable: the focus is still clearly visible.

Rules for good focus styles

  1. Never remove the outline without a replacement.
  2. Make it contrast with its surroundings (at least 3:1).
  3. Make it thick enough to notice: 2 or 3 pixels.
  4. Use outline or box-shadow, not a color change alone.
dangerous
No outline: none on its own
:focus { outline: none; } with nothing else makes a site unusable by keyboard. This is one of the most common accessibility failures. See CSS Outline.