Skip to main content

Frontend development · Beginner · 17 min

Style keyboard focus with :focus-visible

By Padding · Updated 18 Nov 2026
Modern browsers · CSS Selectors Level 4 and CSS Color Adjustment Level 1 · checked in Chromium with Playwright 1.65.1

You will remove an outline reset that hides keyboard focus, add a two-colour focus ring with :focus-visible that stays visible on white, tinted and accent backgrounds, keep it clear of a sticky header with scroll-margin, check it in forced colours mode and prove it all with a Playwright keyboard test.

On this page

A keyboard user moves through a page with Tab and Shift+Tab, and the focus ring is the only thing that tells them where they are. Remove it and the page still works, but they are typing blind. One line causes most of these failures: :focus { outline: none; }, copied in from an old reset or added because someone disliked the ring after a mouse click.

This tutorial fixes that line on a small page and then builds the replacement properly. The page is a one-page stand-in for the Larkfield Clinic booking app, the fictional community clinic used across this library: a white Choose a service section, a tinted Pick a time section, a dark teal Confirm section and a Your details form, under a sticky header. The example booking is the usual one, a Nurse appointment on Tuesday 9 December at 10:30.

You finish with a focus style you can paste into any project and a Playwright script that presses Tab through the page and fails if a ring goes missing. The design reasoning behind the ring (shape, thickness, where it sits on each component) is in Design visible focus states for keyboard users. This is the CSS.

Step 1 · Build the page with the bug in it

Make a folder and the page. It loads three stylesheets: reset.css (where the bug lives), style.css for the look of the page, and focus.css, empty for now, which will hold everything this tutorial adds:

Bash
mkdir -p ~/focus-ring-demo
cd ~/focus-ring-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Focus ring demo</title>
  <link rel="stylesheet" href="reset.css">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="focus.css">
</head>
<body>
  <header class="site-header">
    <a class="brand" href="#top" id="brand">Larkfield Clinic</a>
    <nav aria-label="Booking">
      <a href="#time" id="nav-time">Pick a time</a>
      <a href="#details" id="nav-details">Your details</a>
    </nav>
  </header>
  <main id="top">
    <section class="panel" id="service">
      <h2>Choose a service</h2>
      <p>Nurse appointment</p>
      <a href="#service" id="change-service">Change service</a>
    </section>
    <section class="panel panel-tint" id="time">
      <h2>Pick a time</h2>
      <p>Tuesday 9 December, 10:30</p>
      <a href="#time" id="other-days">See other days</a>
    </section>
    <section class="panel panel-accent" id="confirm">
      <h2>Confirm</h2>
      <p>Nurse appointment, Tuesday 9 December, 10:30</p>
      <button type="button" id="book">Book appointment</button>
    </section>
    <section class="panel" id="details">
      <h2>Your details</h2>
      <label for="name">Full name</label>
      <input id="name" name="name" autocomplete="name">
    </section>
  </main>
  <footer class="site-footer">
    <p>Larkfield Clinic</p>
    <a href="#top" id="back-to-top">Back to top</a>
  </footer>
</body>
</html>
HTML

Now the three stylesheets. The reset has the problem line at the bottom. The page styles use the Larkfield colour tokens, and each section is tall enough that the page scrolls under the sticky header:

Bash
cd ~/focus-ring-demo
cat > reset.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; }
:focus { outline: none; }
CSS
cat > style.css <<'CSS'
:root {
  --colour-text: #1b1f24;
  --colour-surface: #ffffff;
  --colour-line: #d5d9df;
  --colour-border: #7d8592;
  --colour-accent: #0f5e5a;
  --colour-accent-tint: #e3f0ee;
  --colour-on-accent: #ffffff;
}
body {
  font-family: system-ui, sans-serif;
  line-height: 1.5;
  color: var(--colour-text);
  background: var(--colour-surface);
}
a { color: inherit; }
.site-header {
  position: sticky;
  top: 0;
  z-index: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  align-items: center;
  justify-content: space-between;
  min-height: 4rem;
  padding: 0.75rem 1rem;
  background: var(--colour-surface);
  border-bottom: 1px solid var(--colour-line);
}
.site-header nav { display: flex; gap: 1rem; }
.panel { min-height: 80vh; padding: 2rem 1rem; }
.panel h2 { margin-top: 0; }
.panel-tint { background: var(--colour-accent-tint); }
.panel-accent { background: var(--colour-accent); color: var(--colour-on-accent); }
button {
  font: inherit;
  font-weight: 600;
  min-height: 3rem;
  padding: 0 1.25rem;
  border: 0;
  border-radius: 0.5rem;
  background: var(--colour-on-accent);
  color: var(--colour-accent);
}
label { display: block; font-weight: 600; }
input {
  font: inherit;
  min-height: 3rem;
  padding: 0 0.75rem;
  border: 1px solid var(--colour-border);
  border-radius: 0.5rem;
}
.site-footer { min-height: 40vh; padding: 2rem 1rem; border-top: 1px solid var(--colour-line); }
CSS
printf '/* Focus styles go here. */\n' > focus.css

Check it worked

On a Mac, use Chrome or Edge for the keyboard checks in this tutorial. Safari skips links when you press Tab unless you turn on "Press Tab to highlight each item on a webpage" in Safari Settings, Advanced, and Firefox on macOS can skip links unless Keyboard navigation is turned on in System Settings, Keyboard. Without those settings, Tab would seem to do nothing on this page, whatever the CSS says.

Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). Click once on empty page background, then press Tab three times: that passes Larkfield Clinic, Pick a time and Your details. Now press Enter. The page jumps to the Your details section, so focus was on that link even though you could not see it anywhere. That is what a keyboard user gets on every site with this reset.

Step 2 · Find and remove the outline reset

In a real project the line can be anywhere: a reset file, a component library's base styles, or a quick fix in a component. Search for any rule that sets the outline to none or 0. Run this from the project folder:

Bash
cd ~/focus-ring-demo
grep -rnE 'outline:[[:space:]]*(none|0)' --include='*.css' .

It prints ./reset.css:3::focus { outline: none; }. Rewrite the reset without that line:

Bash
cd ~/focus-ring-demo
cat > reset.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; }
CSS
grep -rnE 'outline:[[:space:]]*(none|0)' --include='*.css' . || echo "No outline resets found"

Not every match is a bug. outline: none is fine when the same rule draws a replacement indicator, and you will meet one legitimate case in the forced colours step. A match with nothing in its place is the bug. Older code often has :focus:not(:focus-visible) { outline: none; }, a workaround from before browsers supported :focus-visible. Every current browser supports it, so that rule can go too.

Check it worked

The second search prints No outline resets found. Reload the page, click the background and press Tab. The browser's own focus ring is back. Tab down to "Book appointment" on the teal section: the default ring there is hard to make out against the dark background. Fixing that is the next two steps.

Step 3 · Add a focus ring with :focus-visible

:focus matches whenever an element has focus, however it got there. :focus-visible matches only when the browser judges that the user needs to see focus: after keyboard navigation, and always for text fields, because you type into them. A mouse click on a button or link focuses it without matching :focus-visible. Styling :focus-visible gives keyboard users a strong ring and leaves mouse users undisturbed, which removes the usual reason for deleting the ring in the first place.

Write the first version of the ring into focus.css. The colour comes from a custom property, so a theme can change it in one place:

Bash
cd ~/focus-ring-demo
cat > focus.css <<'CSS'
:root {
  --focus-outer: #1b1f24;
}

:focus-visible {
  outline: 2px solid var(--focus-outer);
  outline-offset: 2px;
}
CSS

Why outline and not border: an outline is drawn outside the element without taking up layout space, so nothing on the page shifts when it appears. outline-offset pushes it 2 pixels away from the element, so the ring does not touch the button's edge. Current browsers draw the outline following border-radius, so the rounded button gets a rounded ring.

On a phone the same rules help people who pair a Bluetooth or USB keyboard with an Android phone or tablet. Chrome for Android supports :focus-visible, so the ring behaves there as it does on a desktop. A thick, high-contrast ring also survives a dim, budget screen in bright daylight better than a thin pale one.

Check it worked

Reload, click the background and press Tab. "Larkfield Clinic" gets a 2 pixel near-black ring with a small white gap. Keep pressing Tab: the ring is clear on the white and tinted sections. Click "Book appointment" with the mouse: it is focused but shows no ring. Click into the "Full name" field with the mouse: it does show a ring, because it is a text field. On the teal section, though, the near-black ring around "Book appointment" is faint. Its contrast against the teal #0f5e5a is 2.18:1, under the 3:1 that WCAG's non-text contrast criterion asks of focus indicators.

Step 4 · Make the ring two colours so it works on any background

One colour cannot contrast with every background: near-black disappears on dark teal, and white disappears on white. Two colours can. Add a white band directly around the element and keep the near-black outline outside it. On a light background the dark outline does the work. On a dark background the white band does.

There is arithmetic behind this. The near-black #1b1f24 and white have a contrast ratio of 16.56:1. For any background between them, its contrast with the near-black multiplied by its contrast with white is exactly 16.56, so one of the two is at least 4:1 (the square root of 16.56). A background darker than the near-black contrasts with white even more. Here, near-black on the tint #e3f0ee is 14.17:1, and white on the teal is 7.58:1.

Replace focus.css with the two-colour version. The white band is a box-shadow with a 2 pixel spread and no blur, which fills exactly the 2 pixel gap that outline-offset leaves. That gives the two 2 pixel bands from the design sheet in Design visible focus states for keyboard users: white touching the control, near-black outside it, 4 pixels in all on every side:

Bash
cd ~/focus-ring-demo
cat > focus.css <<'CSS'
:root {
  --focus-outer: #1b1f24;
  --focus-inner: #ffffff;
}

:focus-visible {
  outline: 2px solid var(--focus-outer);
  outline-offset: 2px;
  box-shadow: 0 0 0 2px var(--focus-inner);
}
CSS

The outline carries the ring and the shadow only adds the white band. That order matters later: forced colours mode removes shadows but keeps outlines.

If one of your components already uses box-shadow for elevation, this rule replaces that shadow while the component has focus. List both shadows on that component's own :focus-visible rule, separated by a comma, so it keeps its elevation.

Check it worked

Reload and Tab through every stop. On white and tinted sections you see the dark ring with a white gap. On the teal section, "Book appointment" now sits inside a clear white band with a dark edge, and the band is easy to see from across the room. Tab to "See other days" on the tinted section: the white band shows against the tint, and the dark outline stands out around it.

Step 5 · Keep focus clear of the sticky header

A sticky header covers the top of the page. When focus moves to an element that is partly behind the header, the browser may decide it is already on screen and not scroll, so the ring sits under the header where nobody can see it. WCAG 2.2 added a criterion for this, 2.4.11 Focus Not Obscured (Minimum), at level AA: the focused element must not be entirely hidden by content the author added, such as a sticky header.

The easiest place to see it is an in-page link. Click "Your details" in the header. The browser scrolls the Your details section to the very top of the window, and its heading ends up hidden behind the header. Keyboard focus has the same problem when a focusable element is partly under the header as you Tab to it.

scroll-margin-top fixes both cases. It adds space above an element whenever the browser scrolls it into view, whether for an in-page link or for keyboard focus. Give it to everything that can take focus or be a link target. The header is 4rem tall, so 5rem leaves a 1rem gap:

Bash
cd ~/focus-ring-demo
cat >> focus.css <<'CSS'

:where(a, button, input, select, textarea, summary, [tabindex], [id]) {
  scroll-margin-top: 5rem;
}
CSS

:where() keeps the specificity of that selector at zero, so any component can set its own scroll-margin-top without a fight. If your header grows on narrow screens (this one wraps its links onto a second line on a small phone), raise the value in a media query, or store the header height in a custom property and use that.

The other fix is the one in WCAG technique C43: scroll-padding-top on the html element, the page's scroll container. It reserves the same space from the other side, the container rather than the element, and the browser uses it for link targets and keyboard focus alike, so html { scroll-padding-top: 5rem; } would pass the same checks in one declaration. Either meets 2.4.11. This tutorial uses scroll-margin-top because it also works when an element scrolls inside a panel of its own, where padding on html has no effect, and because one component can ask for more space than the rest. If you prefer C43, set only one of the two: they add together.

Check it worked

Reload and click "Your details" in the header. The "Your details" heading now sits just below the header with a gap, not behind it. Press Tab: focus goes to the "Full name" field, ring and all. The keyboard case, a button half under the header when Tab reaches it, is hard to set up by hand, so the script in the last step checks it for you.

Step 6 · Check the ring in forced colours mode

Forced colours mode, which Windows calls a contrast theme, replaces the page's colours with a small palette the user chose. People with low vision or light sensitivity use it. In this mode the browser overrides background, text, border and outline colours with system colours and removes every box-shadow. A focus ring drawn only with box-shadow disappears. Yours is drawn with outline, so it survives in the theme's colour.

To check it in Chrome or Edge without changing your system: open DevTools, open the command menu with Ctrl+Shift+P (Cmd+Shift+P on macOS), type "Rendering" and open the Rendering tab, then set "Emulate CSS media feature forced-colors" to forced-colors: active. On Windows 11 you can also turn on a contrast theme in Settings under Accessibility, Contrast themes.

If a component you cannot change draws focus with a shadow only, give it a transparent outline as well. In normal mode it is invisible; in forced colours mode the browser replaces the transparent colour with a system colour and the ring appears:

CSS
.legacy-card:focus-visible {
  outline: 2px solid transparent;
  box-shadow: 0 0 0 2px #0f5e5a;
}

This is the legitimate outline override promised in the search step: the outline is still there, it is only transparent.

Check it worked

With forced colours emulation on, reload and Tab through the page. The teal and tinted sections lose their backgrounds, the white band around the ring is gone, and every focused element still has a 2 pixel ring in the theme's colour. Turn emulation off again before the next step.

Step 7 · Test the ring with a keyboard script

Checking by eye works once. A script catches the next time someone adds outline: none to a component. Install Playwright in the demo folder, with the Chromium browser it drives. On Linux, --with-deps also installs the system libraries Chromium needs and asks for your password to do it:

Bash
cd ~/focus-ring-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromium

The script presses Tab through the whole page and checks every stop for the two-colour ring, clicks the button with the mouse and checks for no ring, puts the button under the sticky header and checks that Tab brings it out, and repeats the ring check with forced colours emulated:

Bash
cd ~/focus-ring-demo
cat > check-focus.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';

const url = new URL('./index.html', import.meta.url).href;
const browser = await chromium.launch();
const open = async (forcedColors = 'none') => {
  const page = await browser.newPage({ viewport: { width: 800, height: 600 } });
  await page.emulateMedia({ forcedColors });
  await page.goto(url);
  return page;
};
const ring = (page, sel) =>
  page.$eval(sel, (el) => {
    const s = getComputedStyle(el);
    return { style: s.outlineStyle, width: s.outlineWidth, colour: s.outlineColor, shadow: s.boxShadow };
  });
const focusedId = (page) => page.evaluate(() => document.activeElement.id);
const tabOrder = ['brand', 'nav-time', 'nav-details', 'change-service', 'other-days', 'book', 'name', 'back-to-top'];

// Every Tab stop shows the two-colour ring
let page = await open();
for (const id of tabOrder) {
  await page.keyboard.press('Tab');
  assert.equal(await focusedId(page), id, `Tab reaches #${id}`);
  const r = await ring(page, `#${id}`);
  assert.equal(r.style, 'solid', `#${id} has an outline`);
  assert.equal(r.width, '2px', `#${id} outline is 2px`);
  assert.equal(r.colour, 'rgb(27, 31, 36)', `#${id} outline is near-black`);
  assert.match(r.shadow, /^rgb\(255, 255, 255\) 0px 0px 0px 2px/, `#${id} has the white band`);
}
console.log(`keyboard: ${tabOrder.length} stops, two-colour ring on each`);

// A mouse click on the button focuses it without a ring
await page.click('#book');
assert.equal(await focusedId(page), 'book');
assert.equal((await ring(page, '#book')).style, 'none', 'no ring after a mouse click');
console.log('mouse: no ring on click');
await page.close();

// Focus is not hidden by the sticky header
page = await open();
await page.evaluate(() => {
  const top = document.querySelector('#book').getBoundingClientRect().top;
  window.scrollBy(0, top - 20);
  document.querySelector('#other-days').focus({ preventScroll: true });
});
await page.keyboard.press('Tab');
assert.equal(await focusedId(page), 'book');
const gap = await page.evaluate(() => {
  const ringTop = document.activeElement.getBoundingClientRect().top - 4;
  return Math.round(ringTop - document.querySelector('.site-header').getBoundingClientRect().bottom);
});
assert.ok(gap >= 0, `ring is below the header (gap ${gap}px)`);
await page.click('#nav-details');
const headingGap = await page.evaluate(() =>
  Math.round(document.querySelector('#details').getBoundingClientRect().top - document.querySelector('.site-header').getBoundingClientRect().bottom));
assert.ok(headingGap >= 0, `Your details is below the header (gap ${headingGap}px)`);
console.log('sticky header: focus and link target stay in view');
await page.close();

// Forced colours: the outline stays, the shadow goes
page = await open('active');
assert.ok(await page.evaluate(() => matchMedia('(forced-colors: active)').matches), 'forced colours emulated');
for (const id of tabOrder) {
  await page.keyboard.press('Tab');
  if (id !== 'book') continue;
  const r = await ring(page, '#book');
  assert.equal(r.style, 'solid', 'outline survives forced colours');
  assert.equal(r.width, '2px');
  assert.equal(r.shadow, 'none', 'shadow is removed');
  assert.doesNotMatch(r.colour, /, 0\)$/, 'outline colour is not transparent');
}
console.log('forced colours: outline kept, shadow removed');
await page.close();
await browser.close();
JS
node check-focus.mjs

The ring's top edge is 4 pixels above the element (2 pixels of offset plus 2 of outline), which is why the script subtracts 4 before comparing it with the header.

Check it worked

The script prints four lines and exits without an error:

Text
keyboard: 8 stops, two-colour ring on each
mouse: no ring on click
sticky header: focus and link target stay in view
forced colours: outline kept, shadow removed

Now break it on purpose. Add :focus { outline: none; } to the end of focus.css and run node check-focus.mjs again: it stops with an AssertionError and the message #brand has an outline. Remove the line and it passes again. The same line in reset.css would not break the ring, because focus.css loads later and its :focus-visible rule has the same specificity, so it wins. Load order is a fragile defence, which is why the search in step 2 removes the reset anyway. Add this script to your project's test run so a missing ring fails the build.

Step 8 · Clean up

Delete the demo folder, including the Playwright packages installed in it:

Bash
cd ~
rm -rf ~/focus-ring-demo

Playwright keeps its downloaded browsers in a shared cache (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS). Leave it if other projects use Playwright, or delete that folder to get the space back.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.