completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Focus delegation and focus styles

Learn web component focus styles: when to use delegatesFocus or a tabindex on the host, :focus-visible in shadow DOM, and focus rings with 3:1 contrast.

By the end, you can
  • 01
    Pick how the host takes focusDelegate focus when the component wraps a real control, give the host a tabindex when the host is the control, and never mix a role on the host with delegation.
  • 02
    Show keyboard focus, inside and outStyle focus with :focus-visible on the right element, with :host() from inside and ::part() from the page.
  • 03
    Make the ring easy to seeCheck a ring at 3:1 against every background it sits on, and keep it visible in forced colors mode.

How do you make a web component act like one control?

Ravi has made a search box for Leaf and Kettle's menu. It's a tag called <tea-search>. Inside its shadow root sit a small magnifier picture and a text box. Asha tries it. She clicks the magnifier, because that's where her eye goes. Nothing happens. She has to click again, on the text box, to start typing.

To Asha, the magnifier and the box are one thing: the search. How does Ravi make the whole tag act like one control? And when someone moves through the page with the Tab key, how do they see where they are?

When a component wraps a real control, attach its shadow root with delegatesFocus: true. Then a click anywhere on the host, a call to focus(), or a press of Tab puts focus on the control inside. When the host is the control itself, give it tabindex="0" instead. Either way, show keyboard focus with a :focus-visible ring that has 3:1 contrast against what's around it.

You met delegatesFocus in lesson 9.3. It made the kit's quantity take focus like one control. This lesson goes further. Here is Ravi's search box with the option turned on. Its class is in the tea-search.js tab:

A search box whose shadow root delegates focusPop out in the code editor (opens in a new tab)HTML
<tea-search></tea-search><script src="tea-search.js"></script><script>  const search = document.querySelector("tea-search");  search.addEventListener("focusin", () => {    console.log("Focus is in:", search.shadowRoot.activeElement.id);  });</script>
ResultLoading…
  • In the tea-search.js tab, line 4 attaches the shadow root with delegatesFocus: true.
  • Lines 12 to 15 draw the magnifier, an SVG picture. aria-hidden="true" keeps it out of what a screen reader reads. Line 16 is the text box, with the id box.
  • Lines 6 to 10 give the field its look. The section on contrast comes back to lines 8 and 9.
  • On the page, lines 5 to 7 print the id of the element that gets focus inside the shadow root.

Click the magnifier. The console prints Focus is in: box, and you can type at once. The picture can't take focus, so the host handed it to the box.

Three ways into a search box. Left, three cards: click the magnifier, search.focus(), and press Tab. Right, a window titled tea-search holds a magnifier card and an input card with the id box. The click arrow goes to the magnifier, and an arrow labelled handed on goes from the magnifier down to the input. The other two arrows go straight to the input. A note under them says the host matches :focus.click the magnifiersearch.focus()press Tabtea-searchmagnifier<input id="box">the host matches :focushanded on
Every way in ends in the text box. The magnifier can't take focus, so the click is handed on. The host never holds focus itself, but it matches :focus while the box does.
Real-life analogyA door that opens straight into the tasting room

Leaf and Kettle's tasting room has a swinging door. Push the glass, the frame, or the handle: it opens, and you are in the room. Nobody stops in the doorway. While someone is inside, a Room in use sign lights up outside.

In real life: Pushing on the glass, the frame, or the handle
In JavaScript: A click on the magnifier, or on the field's edge
In real life: The tasting room
In JavaScript: The text box inside the shadow root
In real life: Nobody stands in the doorway
In JavaScript: The host never has focus itself
In real life: The Room in use sign outside
In JavaScript: The host matching :focus
The main idea

A host acts like one control in one of two ways. It hands focus to the real control inside, with delegatesFocus. Or it is the control, and takes focus itself, with a tabindex. Either way, a ring shows where keyboard focus is, clearly enough to see.

Why it matters: people click the part of a control they see. If only the text box works, a click on its picture, its label, or its padding is wasted. And people who use the keyboard can only use what they can find.

What happens when a shadow root delegates focus?

Lesson 9.3 showed two ways in: focus() on the host, and a click on plain text. Here are four, on one page. The page prints a line each time focus goes into the search box:

Four ways into the search boxPop out in the code editor (opens in a new tab)HTML
<button id="before">Before</button><tea-search></tea-search><button id="call">search.focus()</button><script src="tea-search.js"></script><script>  const search = document.querySelector("tea-search");  document.querySelector("#call").addEventListener("click", () => search.focus());  search.addEventListener("focusin", () => {    const inside = search.shadowRoot.activeElement.id;    console.log("In:", inside, "| host matches :focus:", search.matches(":focus"));  });</script>
ResultLoading…
  • Lines 1 to 3 are a Before button, the search box, and a button that calls search.focus().
  • Line 7 makes that button call focus() on the host.
  • Lines 8 to 11 run when focus goes in. Line 9 reads the id of the focused element inside. Line 10 also asks whether the host matches :focus.

Try each one. Click Before in between, so focus leaves the box each time:

  1. Click the magnifier.
  2. Click the thin strip just inside the border, left of the magnifier.
  3. Click Before, then press Tab.
  4. Click the search.focus() button.

Each one prints In: box | host matches :focus: true. The MDN page on delegatesFocus names the first and last: a click on a part that can't take focus, and focus() on the host. Here is what each route does:

  • A click on anything in the host that can't take focus goes up to the host. The host passes it to its first control. The picture, the padding, and the border all count.
  • Tab goes straight to the box. The host is never a stop of its own. The HTML Standard says a host that delegates focus is never focusable itself.
  • focus() on the host focuses the box. blur() on the host takes focus away from the box again.

In every case the box has focus, and the host only matches :focus. So document.activeElement gives tea-search, as in lesson 9.3. When something focuses a delegating host, the standard's steps only look inside it. If focus is already in there, it stays. Otherwise it goes to the focus delegate, which the next part explains.

Why it matters: you don't need click handlers that call input.focus(). One option on attachShadow() covers every route, for mouse and keyboard alike.

Slotted controls and delegatesFocus

Asha builds a tea picker. Its shadow root holds a short label and a slot. The page puts two buttons in the slot. She turns on delegatesFocus and expects focus() to reach the first button. Does it?

A picker that delegates focus, with only slotted buttonsPop out in the code editor (opens in a new tab)HTML
<tea-pick>  <button>Sencha</button>  <button>Oolong</button></tea-pick><button id="call">pick.focus()</button><script>  class TeaPick extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `<span>Pick a tea:</span> <slot></slot>`;    }  }  customElements.define("tea-pick", TeaPick);   const pick = document.querySelector("tea-pick");  document.querySelector("#call").addEventListener("click", () => pick.focus());  document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>
ResultLoading…
  • Lines 1 to 4 are the picker, with two of the page's own buttons inside it.
  • Line 10 delegates focus. Line 11 is the label, then a slot for the buttons.
  • Line 17 calls pick.focus(). Line 18 prints the text of each element that gets focus.

Click pick.focus(). It prints Focus: pick.focus(), for the button you clicked, and then nothing. Focus stays on that button. Click the words Pick a tea: nothing prints. Click Oolong itself, and it prints Focus: Oolong.

The focus delegate, the element the host hands focus to, comes only from the shadow root's own elements. Slotted buttons are the page's elements. They show inside the host, as lesson 8.2 showed, but they never get picked. So a host with nothing focusable in its own shadow root has nobody to hand focus to. Exercise 5 gives the picker a focus() of its own.

Clicks on slotted content work a little differently. Here is a chip: a button in the shadow root, with a slot inside it.

A click on slotted text inside a shadow buttonPop out in the code editor (opens in a new tab)HTML
<tea-chip>Sencha</tea-chip><tea-chip>Oolong</tea-chip><script>  class TeaChip extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `<button><slot></slot></button>`;    }  }  customElements.define("tea-chip", TeaChip);  document.addEventListener("focusin", (event) => {    console.log("Focus:", event.target.textContent, "| inside:", event.target.shadowRoot.activeElement.localName);  });</script>
ResultLoading…
  • Lines 1 and 2 are two chips. Their words are the page's own text.
  • Line 7 has no delegatesFocus. Line 8 wraps the slot in a <button>.
  • Lines 12 to 14 print the chip, and the element inside its shadow root that has focus.

Click the word Oolong. It prints Focus: Oolong | inside: button. The word itself can't take focus. So Chrome looks for something that can, going up the flat tree: from the word to the slot, then to the button around the slot. Chrome has done this since Chrome 133. Before that, it went from the word to the word's parent on the page, the chip, which can't take focus. Chrome's note on the change says it matches Firefox and Safari.

Why it matters: slotted content shows where its slot is, and clicks on it now follow the same path. But to be chosen by delegatesFocus, a control has to live in the shadow root.

Should a custom element have a tabindex?

Give it tabindex="0" only when the host itself is the control. The kit's switch, tea-toggle, is one. Its role and its checked state live in its internals, from lesson 13.2. There is no control inside it to hand focus to. So it puts itself in the Tab order:

The switch's tab stop, from tea-kit/tea-toggle.jsJavaScript
  connectedCallback() {
    if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
  }

Line 2 sets tabIndex to 0, which writes tabindex="0" on the tag. It does that only if the page wrote no tabindex, so a tabindex the page wrote wins. It waits for connectedCallback(), because a constructor that adds an attribute makes document.createElement() throw, as lesson 3.2 showed.

The tabindex attribute takes three kinds of value. Each one means something different on a host:

  • tabindex="0" makes the element a Tab stop, in page order. Use it when the host is the control.
  • tabindex="-1" lets code and clicks focus it, but Tab skips it. Use it for something you only focus from code, like a panel you just opened.
  • A positive number moves the element ahead of the others. Never use one. It only sorts within its own group, as lesson 9.3 showed, and MDN says to use only 0 and -1.

What happens when you mix a tabindex with delegation? Try all four ways:

Playground: where does Tab stop?
Before, a search box, and AfterPop out in the code editor (opens in a new tab)HTML
<button id="before">Before</button><tea-search></tea-search><button id="after">After</button><script>  class TeaSearch extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `<span>Search</span> <input id="box" aria-label="Search teas">`;    }  }  customElements.define("tea-search", TeaSearch);   const where = () => {    let element = document.activeElement;    while (element.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;    return element.id || element.localName;  };  document.addEventListener("click", () => console.log("Click. Focus:", where()));  document.addEventListener("keyup", (event) => {    if (event.key === "Tab") console.log("Tab. Focus:", where());  });</script>
ResultLoading…
Try it yourself
One stop, in the box

Click Before, then press Tab twice. It prints Tab. Focus: box, then Tab. Focus: after. The host is never a stop. Click the word Search: Click. Focus: box.

Only lines 2 and 8 change. Click Before in the result, then press Tab until focus reaches After. The page prints each stop, and each click.
  • Line 2 is the host. The playground gives it a tabindex, or none.
  • Line 8 attaches the shadow root, with or without delegatesFocus. Line 9 is the word Search and the box.
  • Lines 14 to 18 walk down to the element that really has focus, as in lesson 9.3. Lines 19 to 22 print it after each click, and after each Tab.

Here is what each choice prints, from a click on Before:

  • delegatesFocus alone stops at box, then after. One stop for one control.
  • tabindex="0" without it stops at tea-search, then box, then after. A click on the word focuses the host, not the box.
  • Both stops at box, then after. The tabindex changes nothing.
  • delegatesFocus and tabindex="-1" goes straight to after. A click on the word still reaches the box.
Two rows of Tab stops. Top row, delegatesFocus: true: Before, then box, then After, labelled one stop. Bottom row, tabindex 0 with no delegatesFocus: Before, then tea-search, then box, then After, labelled two stops. A note under tea-search says the host is a stop of its own.delegatesFocus: trueBeforeboxAfterone stoptabindex="0", no delegatesFocusBeforetea-searchboxAftertwo stopsthe host is a stop of its own
With delegation, Tab goes straight into the box. A host with tabindex="0" that doesn't delegate is a stop of its own, so one search box takes two presses of Tab.
Real-life analogyA door you knock on first

The office at Leaf and Kettle has a door you knock on. You wait, someone opens it, and then you walk in: two steps to get where you were going. The tasting room's swinging door takes one. And the door bell beside the office is a control all by itself. You press the bell, and that's the whole job.

In real life: Knocking, and waiting at the door
In JavaScript: The first Tab stops on the host
In real life: Being let into the room
In JavaScript: The second Tab reaches the box
In real life: The tasting room's swinging door
In JavaScript: delegatesFocus: one Tab, straight in
In real life: The office's door bell
In JavaScript: A host that is the control, like the switch

Why does -1 skip the box? The HTML Standard builds the Tab order from groups, one for each shadow host. It leaves out every group whose host has a negative tabindex. So a negative tabindex on a host takes its whole shadow root out of the Tab order. Quiz question 3 shows it happens without delegation too.

Read each row of the table across, to choose between the two ways:

Delegate focus, or a tabindex on the host?
QuestionThe host delegates focusThe host has tabindex="0"
When do you use it?When the component wraps a real control, like an input or a button.When the host is the control, with its own role and state.
Where does focus land?On the control inside. document.activeElement is the host.On the host itself.
How many Tab stops?One for each control inside. The host is never a stop.One, on the host.
Does :host(:focus) match?Yes, while the control inside has focus.Yes, while the host has focus.
Does :host(:focus-visible) match?No, not in Chrome. Style the control inside.Yes, on keyboard focus.
Who has the role and state?The control inside, like <input type="search">.The host, through its internals.
Delegate focus or a tabindex?
  • tea-search: a magnifier and an <input> in its shadow root.
  • tea-toggle: a switch whose role and checked state come from its internals.
  • tea-quantity: a - button, a number, and a + button.
  • tea-card: a box with a name, a price, and buttons inside.
  • tea-rating: stars whose host has the role slider and a value, set in its internals.
  • tea-badge: a label like Organic.
Try it yourself
0 of 6 correct

Sort each kit component by how its host should take focus.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Why it matters: one control should be one Tab stop. A tabindex on a host that wraps a control makes keyboard users press Tab twice. And a negative tabindex can hide a whole component from them by mistake.

Can a host with a role also delegate focus?

It can, and it shouldn't. Say Ravi builds the switch another way. He gives the host its role and state, as before. But he wraps the label in a <button>, so a real button handles clicks and keys, and turns on delegatesFocus. Compare it with the kit's way. Lesson 13.1 showed how to read Chrome's accessibility tree, the list a screen reader reads:

Playground: where does focus land on a switch?
A switch with its role in its internalsPop out in the code editor (opens in a new tab)HTML
<button id="before">Before</button><tea-toggle>Add milk</tea-toggle><script>  class TeaToggle extends HTMLElement {    #internals = this.attachInternals();    constructor() {      super();      this.#internals.role = "switch";      this.#internals.ariaChecked = "false";      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `<button><slot></slot></button>`;    }    connectedCallback() {      // No tab stop here: the button inside takes focus.    }  }  customElements.define("tea-toggle", TeaToggle);  document.addEventListener("keyup", (event) => {    if (event.key === "Tab") console.log("Focus is on:", event.composedPath()[0].localName);  });</script>
ResultLoading…
Chrome's accessibility tree after one TabText
button "Before"
switch "Add milk", checked: false
  button "Add milk", focused: true
Try it yourself
Focus skips the switch

Tab prints Focus is on: button. The switch in the tree has its role and its state, but focus is on the button inside it. A screen reader reads what has focus: a button called Add milk.

Lines 10, 11, and 14 change. Click Before in the result and press Tab. The tree under the code is Chrome's, after that Tab.
  • Lines 8 and 9 give the host the role switch, and the state not checked, in both choices.
  • Line 10 attaches the shadow root. Line 11 fills it: a button around the slot, or the slot alone.
  • Line 14 adds the tab stop, or doesn't. Lines 18 to 20 print the tag that Tab lands on.

With delegation, Tab prints Focus is on: button. In the tree, the switch has its role and its checked: false, but focused: true sits on the button inside it. A screen reader reads the element that has focus. Here that's a button called Add milk. Whether milk is on never comes up.

With the tabindex, Tab prints Focus is on: tea-toggle. The focused node is the switch itself, with its state. Chrome's guide to accessible web components says exactly this: don't combine delegatesFocus with a role and state on the host, or focus lands inside and skips the host's state.

Two halves. Left, role on the host and delegatesFocus: a card switch Add milk, checked: false, and under it a card button Add milk. Focus lands on the button, and the switch's state is skipped. Right, role and tabindex on the host: one card switch Add milk, checked: false. Focus lands on the switch, so its state comes with focus.Role on the host, delegatesFocusswitch "Add milk", checked: falsebutton "Add milk"focus lands on the buttonthe switch's state is skippedRole and tabindex on the hostswitch "Add milk", checked: falsefocus lands on the switchits state comes with focus
Chrome's tree for each switch after one Tab. On the left, focus is on a plain button inside the switch. On the right, it's on the switch, with its checked state.
Real-life analogyA light switch behind a cupboard door

In the dark, you find a light switch by touch. Your fingers tell you at once if it's up or down. Now put the switch inside a cupboard, behind a little door. Your hand finds the cupboard's handle, and learns nothing about the light.

In real life: Putting your hand on the switch
In JavaScript: Focus landing on the host
In real life: Feeling whether it's up or down
In JavaScript: Hearing the switch's checked state
In real life: A cupboard door in front of the switch
In JavaScript: A button inside a host that delegates focus
In real life: Your hand on the cupboard's handle
In JavaScript: Focus on the inner button

The rule from Chrome's guide, in short: the element with the role and state is the one that takes focus. If the role is on the host, focus goes on the host. If the role belongs to a real control inside, delegate to it.

Why it matters: the bug is easy to miss. The switch looks fine and clicks fine. Only a screen reader, or the tree, shows that its state is never read.

How does :focus-visible work in shadow DOM?

Focus is only useful if people can see it. The :focus-visible pseudo-class matches a focused element when the browser thinks a ring would help. Lesson 10.2 used it for the tabs' ring. When does it match? Try it on a button and a text box:

When :focus-visible matchesPop out in the code editor (opens in a new tab)HTML
<tea-order></tea-order><script>  class TeaOrder extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open" });      this.shadowRoot.innerHTML = `        <style>:focus-visible { outline: 3px solid seagreen; outline-offset: 2px; }</style>        <button id="add">Add 1</button> <input id="note" aria-label="Note">`;      this.shadowRoot.addEventListener("focusin", (event) => {        console.log(event.target.id, ":focus-visible", event.target.matches(":focus-visible"));      });    }  }  customElements.define("tea-order", TeaOrder);</script>
ResultLoading…
  • Line 8 draws a ring on whatever matches :focus-visible in the shadow root.
  • Line 9 is a button and a text box.
  • Lines 10 to 12 print the id of each element that gets focus, and whether it matches.
  1. Click Add 1. It prints add :focus-visible false, and no ring shows.
  2. Press Tab. It prints note :focus-visible true.
  3. Press Shift+Tab. It prints add :focus-visible true. The same button has a ring now.
  4. Click in the Note box. It prints note :focus-visible true, even for a click.

MDN explains the rule of thumb. After a click, you know where you clicked, so a button shows no ring. After a key, you need to be shown. A text box always shows one, because you need to see where your typing goes. Chrome also follows the last input when code moves focus: after a key press, focus() shows a ring, and after a click it doesn't. To ask for the ring anyway, call focus() with focusVisible: true. Exercise 6 tries it.

Real-life analogyReading back a phone order

At the counter, a customer points at Sencha on the board. Meena doesn't need to say it back. When someone orders by phone, they can't point. So Meena reads the order back, to be sure they both mean the same tea.

In real life: A customer pointing at the menu
In JavaScript: A click with the mouse
In real life: Meena not repeating it
In JavaScript: No ring after the click
In real life: A customer ordering by phone
In JavaScript: Moving with the Tab key
In real life: Meena reading the order back
In JavaScript: A :focus-visible ring

Styling the host's focus

When the host is the control, the ring goes on the host. The kit's switch draws it with :host(:focus-visible). Exercise 2 clicks it with the mouse. But what does a host that delegates focus match?

What a delegating host matches after a TabPop out in the code editor (opens in a new tab)HTML
<button id="start">Start here</button><tea-search></tea-search><script src="tea-search.js"></script><script>  const search = document.querySelector("tea-search");  search.addEventListener("focusin", () => {    const box = search.shadowRoot.activeElement;    console.log("box :focus-visible", box.matches(":focus-visible"));    console.log("host :focus", search.matches(":focus"), "| host :focus-visible", search.matches(":focus-visible"));  });</script>
ResultLoading…
  • Line 1 is a place to start from. Line 2 is Ravi's search box.
  • Line 8 asks about the box. Line 9 asks about the host.

Click Start here, then press Tab. It prints box :focus-visible true and host :focus true | host :focus-visible false. In Chrome, a host that delegates focus matches :focus, but never :focus-visible. A rule like :host(:focus-visible) on it would never draw.

So draw the ring on the element inside. Ravi's search box draws it around the whole field with .field:focus-within. A text box always shows focus, so that's the same moment. For buttons, use button:focus-visible, or the kit's base ring, which matches :focus-visible on every element inside. :host(:focus-within) rings the whole host, but it shows after clicks too.

Styling a part's focus from the page

A page can restyle a component's ring through a part. Lesson 12.2 showed that :focus-visible may follow ::part(). Here the page gives the kit's quantity a dashed ring:

A dashed keyboard ring through the quantity's button partPop out in the code editor (opens in a new tab)HTML
<style>  tea-quantity::part(button):focus-visible { outline: 3px dashed darkblue; }</style><tea-quantity></tea-quantity><script type="module">  import "./tea-kit/index.js";  const quantity = document.querySelector("tea-quantity");  quantity.shadowRoot.addEventListener("focusin", (event) => {    console.log(event.target.id, "outline:", getComputedStyle(event.target).outlineStyle);  });</script>
ResultLoading…
  • Line 2 is the page's rule, for the quantity's two buttons when they show focus.
  • Lines 8 to 10 print each button that gets focus, and its outline style. They listen on the shadow root, because moves between the two buttons never reach the page.

Click - with the mouse. It prints less outline: none. Press Tab. It prints more outline: dashed. The page's rule beats the kit's own ring, as lesson 11.4 showed for any rule from outside.

Here are the selectors side by side. Read each row across:

Which selector draws a keyboard ring?
Where the ring goesFrom inside the shadow rootFrom the page
On the host, when the host is the control.:host(:focus-visible)tea-toggle:focus-visible
On a control inside a host that delegates focus.button:focus-visibletea-quantity::part(button):focus-visible
Around a whole host that delegates focus.:host(:focus-within), which also shows after a click.tea-search:focus-within

Why it matters: a ring on the wrong element never shows. Put it where focus really is, or on the host when the host is the control.

How much contrast does a focus ring need?

A ring people can't see is no ring. The Web Content Accessibility Guidelines, WCAG, set the rules. Each rule is a success criterion with a number and a level: A, AA, or the strictest, AAA. Four of them matter most for a focus ring. Read each row across:

What WCAG 2.2 asks of a focus ring
Success criterionLevelWhat it asks
2.4.7 Focus VisibleAAThere is a way to see keyboard focus. A browser may show it only for the keyboard.
1.4.11 Non-text ContrastAAThe ring has at least 3:1 contrast against the colors next to it.
2.4.11 Focus Not Obscured (Minimum)AAThe focused control isn't hidden completely by something the page drew, like a sticky header. New in WCAG 2.2.
2.4.13 Focus AppearanceAAAThe ring is at least as big as a 2px line around the control, and its pixels change by 3:1. New in WCAG 2.2.

The 2.4.7 page lets a browser show focus only for the keyboard, so :focus-visible is fine. The 1.4.11 page asks for 3:1 against the colors next to the ring. 2.4.11 and 2.4.13 are new in WCAG 2.2. 2.4.13 says a solid 2px outline is the simplest way to meet its size rule.

What is a contrast ratio? First, each color gets a relative luminance: how bright it is, from 0 for black to 1 for white. Then the ratio compares two of them. 1:1 means the same color, and 21:1 is black on white. Here is WCAG's formula as JavaScript:

WCAG's contrast ratio for two colorsPop out in the code editor (opens in a new tab)JavaScript
function luminance([r, g, b]) {
  const channel = (value) => {
    const c = value / 255;
    return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
  };
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}
function contrast(a, b) {
  const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (light + 0.05) / (dark + 0.05);
}
const seagreen = [46, 139, 87];
const white = [255, 255, 255];
console.log(Math.floor(contrast(seagreen, white) * 100) / 100);
console.log(Math.floor(contrast(seagreen, seagreen) * 100) / 100);
  • Lines 1 to 7 find a color's luminance. Line 3 turns each channel into a number from 0 to 1. Line 4 is the curve from WCAG's definition. Line 6 adds the three channels with WCAG's weights, and green counts most.
  • Lines 8 to 11 put the lighter color on top, add 0.05 to each, and divide.
  • Lines 14 and 15 print the ratio, cut to two places. They never round up, because WCAG says 2.999 isn't 3.

It prints 4.24, then 1. A sea green ring on white passes. A sea green ring on sea green can't be seen.

Real-life analogyA high-visibility vest

A road worker wears an orange vest, so drivers see her against the gray road. If she stands in front of an orange wall, the vest disappears. A safe vest is one that shows wherever she has to stand.

In real life: The orange vest
In JavaScript: The focus ring
In real life: The gray road behind the worker
In JavaScript: The color next to the ring
In real life: The orange wall
In JavaScript: A header the same color as the ring
In real life: Checking every place the worker stands
In JavaScript: Checking the ring on every background

Asha's page has a sea green header with the search box, and a white card below. Her ring color comes from one custom property, --tea-focus-ring. Custom properties pass into shadow roots, as lesson 12.1 showed, so one line sets the search box's ring and the card button's ring:

Playground: one ring on two backgrounds
A ring color for the whole pagePop out in the code editor (opens in a new tab)HTML
<style>  :root { --tea-focus-ring: seagreen; }  header { background: seagreen; padding: 12px; }  .card { margin-top: 12px; padding: 8px 12px; border: 2px solid seagreen; border-radius: 8px; background: white; color: black; }  button:focus-visible { outline: 2px solid var(--tea-focus-ring); outline-offset: 2px; }</style><header><tea-search></tea-search></header><div class="card">Sencha <button>Add 1</button></div><script src="tea-search.js"></script>
ResultLoading…
Try it yourself
Lost on the header

On the green header: 1.00:1, fails. On the white card: 4.24:1, passes. The ring is the same color as the header, so there it can't be seen at all.

Only line 2 changes. Click in the search box to see its ring on the header, then press Tab to see the Add 1 button's ring on the card.
  • Line 2 sets the ring color for the whole page. It's the line the playground changes.
  • Line 3 is the header, and line 4 the white card.
  • Line 5 draws the button's ring. The search box draws its own, from line 8 of its file.
Three pairs of colors. Left, on the white card: background white and ring seagreen, 4.24:1, passes. Middle, on the green header: background seagreen and ring seagreen, 1.00:1, fails. Right, on the green header: background seagreen and ring white, 4.24:1, passes.on the white cardbackground: whitering: seagreen4.24:1, passeson the green headerbackground: seagreenring: seagreen1.00:1, failson the green headerbackground: seagreenring: white4.24:1, passes
The same ring color passes on one background and can't be seen on another. Check a ring against every color it sits next to.

Sea green fails on the header, and white fails on the card. Black passes on both. A ring made of two colors works too. WCAG's technique C40 says that if the two colors are 9:1 apart, one of them passes against any plain background. The kit takes another way, in the practical below.

Outline or box-shadow?

Ravi's search box removes the text box's own outline, on line 9 of its file, and draws a new ring on line 8. Removing it is fine only because line 8 replaces it. outline: none with nothing in its place fails 2.4.7. WCAG lists it as failure F78.

The ring can be an outline or a box-shadow. An outline takes no room, so nothing moves when it appears, and outline-offset leaves a gap between it and the control. Some people use forced colors mode, like Windows' high contrast themes. It replaces the page's colors with a small set the person chose. There, the two rings behave differently:

Three keyboard rings, and forced colors modePop out in the code editor (opens in a new tab)HTML
<style>  button { margin: 8px; }  #outline:focus-visible { outline: 2px solid seagreen; outline-offset: 2px; }  #shadow:focus-visible { outline: none; box-shadow: 0 0 0 4px seagreen; }  #both:focus-visible { outline: 2px solid transparent; box-shadow: 0 0 0 4px seagreen; }</style><button id="outline">Outline</button><button id="shadow">Shadow</button><button id="both">Both</button><script>  console.log("Forced colors:", matchMedia("(forced-colors: active)").matches);  document.addEventListener("focusin", (event) => {    const style = getComputedStyle(event.target);    console.log(`${event.target.id}: outline ${style.outlineStyle}, shadow ${style.boxShadow}`);  });</script>
ResultLoading…
  • Line 3 is an outline. Line 4 is only a shadow. Line 5 is a shadow with a see-through outline under it.
  • Line 11 prints whether forced colors mode is on. Lines 12 to 15 print each button's outline and shadow.

Click the page beside the buttons and press Tab three times. Each button prints a ring. Now turn on forced colors. In Chrome's DevTools, open the Rendering tab, and set Emulate CSS media feature forced-colors to forced-colors: active. Then press Run again and Tab through. The lines change:

  • Forced colors: true.
  • outline: outline solid, shadow none. The outline stays, in a color from the forced palette.
  • shadow: outline none, shadow none. The ring is gone.
  • both: outline solid, shadow none. The see-through outline now shows.

MDN says forced colors mode turns box-shadow off, and swaps outline-color for a system color. That's why a transparent outline shows up there: its color is replaced too. Microsoft's Edge team suggests exactly that trick. Lesson 15.1, in Accessible components, covers forced colors in full.

Why it matters: check a ring on every background it can sit on, and draw it with an outline. Then it shows for everyone, high contrast themes included.

Safari has the media feature, but it never matches active, because Apple's systems have no forced colors mode.

Building the kit's search box

Time to put Ravi's search box in the kit, as tea-kit/tea-search.js. It works like the one in this lesson, with the kit's tokens and base sheet from lesson 12.6. Three things to notice in its tab:

  • Line 46 attaches its shadow root with delegatesFocus: true. Lines 21 to 24 are the magnifier, and line 25 the text box, named Search teas.
  • Line 11 removes the text box's outline. Line 14 draws the ring around the whole field instead, in var(--tea-focus-ring, var(--tea-color-leaf, seagreen)).
  • Lines 51 to 53 name the box from a label attribute. Lines 56 to 58 give the page what was typed, as value.

tea-kit/tokens.css gets one more token: --tea-focus-ring: var(--tea-color-leaf);. Every ring in the kit reads it now: the base sheet's ring, the quantity's, the switch's, and the tabs'. With the tokens as they were, every ring is the same sea green as before. Here is the search box over three cards:

The kit's search box in a green headerPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><style>  header { background: var(--tea-color-leaf); padding: 12px; --tea-focus-ring: white; }  ul { list-style: none; padding: 0; display: grid; gap: 8px; }</style><header><tea-search label="Search the menu"></tea-search></header><ul>  <li><tea-card name="Sencha" price="4"></tea-card></li>  <li><tea-card name="Oolong" price="5"></tea-card></li>  <li><tea-card name="Assam" price="3"></tea-card></li></ul><script type="module">  import "./tea-kit/index.js";  const search = document.querySelector("tea-search");  const cards = [...document.querySelectorAll("tea-card")];  search.addEventListener("input", () => {    const words = search.value.trim().toLowerCase();    for (const card of cards) card.parentElement.hidden = !card.getAttribute("name").toLowerCase().includes(words);    const shown = cards.filter((card) => !card.parentElement.hidden).map((card) => card.getAttribute("name"));    console.log("Showing:", shown.join(", "));  });</script>
ResultLoading…
  • Line 3 paints the header in the leaf color. It also sets --tea-focus-ring: white, but only inside the header.
  • Line 6 is the search box, named Search the menu. Lines 8 to 10 are three cards.
  • Lines 16 to 21 run on each input event. The text box's typing events are composed, so the page hears them on the host. Line 17 reads search.value. Line 18 hides each card whose name doesn't match.

Click the magnifier and type as. It prints Showing: Sencha, Assam, then Showing: Assam. The ring around the search box is white on the green header: 4.24:1. Press Tab. Focus moves to the Assam card's - button, with a sea green ring on the white card: 4.24:1 again. One token, set in two places, passes on both.

The JSDoc and custom-elements.json document the search box, its label attribute, its value, and its parts. They add --tea-focus-ring to every component with a ring. This version of the kit is kitAfter141.

Lesson 36.5, in Under the hood, follows how Chrome picks the element to focus, step by step. For moving focus with arrow keys, see the next lesson, and Keyboard and focus on the JavaScript path.

Common mix-ups

  • "A tabindex of 0 on a host that delegates focus adds a second Tab stop." No. A delegating host is never a stop of its own. The second stop comes from tabindex="0" on a host that doesn't delegate.
  • "A tabindex of -1 on a host only takes the host out of the Tab order." No. It takes the whole shadow root out, with every control in it.
  • "delegatesFocus can hand focus to a slotted button." No. It only picks from the shadow root's own elements.
  • "A role on the host and delegatesFocus make one accessible control." No. Focus lands on the element inside, so the host's role and state aren't on the focused element.
  • ":host(:focus-visible) shows a keyboard ring on a delegating host." No. In Chrome, such a host matches :focus but never :focus-visible. Style the element inside.
  • "outline: none is fine with :focus-visible." No. Removing the ring with nothing in its place fails 2.4.7.
  • "A ring that passes on white passes everywhere." No. The same sea green ring is 1:1 on the sea green header.
  • "2.996:1 rounds to 3:1, so it passes." No. WCAG says not to round.
  • "A box-shadow ring works in forced colors mode." No. Forced colors mode turns box-shadow off. Add a transparent outline.

Practice exercises

For each one, ask where focus really is, and who can see it. Then check in the result.

Exercise 1 · Warm-upA slotted button comes first

The search box shows the page's Clear button before its text box. Click search.focus(). What does it print?

<tea-search>  <button slot="clear">Clear</button></tea-search><button id="call">search.focus()</button><script>  class TeaSearch extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `<slot name="clear"></slot> <input id="box" aria-label="Search teas">`;    }  }  customElements.define("tea-search", TeaSearch);  const search = document.querySelector("tea-search");  document.querySelector("#call").addEventListener("click", () => {    search.focus();    console.log("Focus:", search.shadowRoot.activeElement?.id ?? document.activeElement.textContent);  });</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA click on the switch

    Click the kit's Add milk switch with the mouse. What does the page print?

    <tea-toggle>Add milk</tea-toggle><script type="module">  import "./tea-kit/index.js";  const toggle = document.querySelector("tea-toggle");  toggle.addEventListener("focus", () => {    console.log(":focus-visible", toggle.matches(":focus-visible"));  });</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeMake the magnifier work

      A click on the magnifier does nothing. Fix the search box, not the page. What does the console print after a click on the magnifier?

      <tea-search></tea-search><script src="tea-search.js"></script><script>  const search = document.querySelector("tea-search");  search.addEventListener("focusin", () => {    console.log("Focus is in:", search.shadowRoot.activeElement.id);  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA ring for the gray bar

        The search box sits on a dimgray bar, with a sea green ring. Change line 2 to white, then to black. Which of the three colors scores highest?

        <style>  .bar { background: dimgray; padding: 12px; --tea-focus-ring: seagreen; }</style><div class="bar"><tea-search></tea-search></div><script src="tea-search.js"></script><script src="contrast.js"></script><script>  const search = document.querySelector("tea-search");  search.addEventListener("focusin", () => {    const ring = getComputedStyle(search.shadowRoot.querySelector(".field")).outlineColor;    const bar = getComputedStyle(document.querySelector(".bar")).backgroundColor;    console.log("Ring on the bar:", ratio(ring, bar));  });</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeA picker that focuses its first tea

          Make pick.focus() focus the first tea in the picker. What does the page print last, after a click on pick.focus()?

          <tea-pick>  <button>Sencha</button>  <button>Oolong</button></tea-pick><button id="call">pick.focus()</button><script>  class TeaPick extends HTMLElement {    constructor() {      super();      this.attachShadow({ mode: "open", delegatesFocus: true });      this.shadowRoot.innerHTML = `<span>Pick a tea:</span> <slot></slot>`;    }  }  customElements.define("tea-pick", TeaPick);   const pick = document.querySelector("tea-pick");  document.querySelector("#call").addEventListener("click", () => pick.focus());  document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA ring after Choose cups

            Choose cups moves focus to the quantity, but no ring shows. Make it show. What does the console print after a click on Choose cups?

            <button id="choose">Choose cups</button><tea-quantity></tea-quantity><script type="module">  import "./tea-kit/index.js";  const quantity = document.querySelector("tea-quantity");  document.querySelector("#choose").addEventListener("click", () => quantity.focus());  quantity.shadowRoot.addEventListener("focusin", (event) => {    console.log(event.target.id, ":focus-visible", event.target.matches(":focus-visible"));  });</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask which element has focus, and what a person can see.

              The focus delegation quiz · 8 questionsScore: first tries count
              1. Question 1 of 8Asha clicks the magnifier in a tea-search whose shadow root delegates focus. What has focus then?

                Choose an answer to see the explanation.

              2. Question 2 of 8A host delegates focus and also has tabindex="0". Its shadow root holds one text box. How many times does Tab stop there?

                Choose an answer to see the explanation.

              3. Question 3 of 8This host has tabindex="-1" and doesn't delegate focus. Asha clicks Before and presses Tab. Where does focus go?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <button>Before</button>
                <tea-note tabindex="-1"></tea-note>
                <button>After</button>
                <script>
                  customElements.define("tea-note", class extends HTMLElement {
                    constructor() {
                      super();
                      this.attachShadow({ mode: "open" }).innerHTML = `<input aria-label="Note">`;
                    }
                  });
                </script>

                Choose an answer to see the explanation.

              4. Question 4 of 8Ravi gives a host the role switch and a checked state, and attaches its shadow root with delegatesFocus: true around a button. A keyboard user tabs to it. What has focus?

                Choose an answer to see the explanation.

              5. Question 5 of 8The text box inside a delegating tea-search has keyboard focus. Which selectors match the host in Chrome?

                Choose an answer to see the explanation.

              6. Question 6 of 8A ring color measures 2.996:1 against the header behind it. Does it meet SC 1.4.11?

                Choose an answer to see the explanation.

              7. Question 7 of 8A button's ring is outline: none; box-shadow: 0 0 0 4px seagreen. What happens in forced colors mode?

                Choose an answer to see the explanation.

              8. Question 8 of 8Which WCAG 2.2 success criterion asks, at Level AA, for a way to see keyboard focus?

                Choose an answer to see the explanation.

              Key takeaways

              • With delegatesFocus: true, a click on any part that can't take focus and focus() land on the first control inside, and Tab skips the host.
              • A delegating host is never focused itself, and never a Tab stop. It matches :focus while the inside has focus.
              • Only controls in the shadow root can be chosen. Slotted controls never are.
              • Give the host tabindex="0", in connectedCallback(), only when the host is the control.
              • tabindex="-1" on a host hides its whole shadow root from Tab. Never use a positive tabindex.
              • Don't put a role and state on a host that delegates focus. Focus would skip them.
              • Style keyboard focus with :focus-visible: on the host when it's the control, on the element inside when it delegates, and through ::part() from the page.
              • A ring needs 3:1 against every color next to it. Never round the ratio.
              • Draw rings with an outline. Forced colors mode turns box-shadow off.

              Remember the one-liner.
              Focus goes where the role is. Delegate to a real control inside, or put the tabindex on a host that is the control. Then show focus with a ring people can see.

              Sources

              The facts on this page come from these standards, docs, and posts:

              Coming next: Keyboard navigation with roving tabindex. It moves focus between items with the arrow keys, with one Tab stop for the whole group.

              CompleteFrontend Clear concepts. Working examples.