Skip to content

Keep your coding agent up to date with the latest web best practices

Release v1.0.0

github-actions[bot]4dd968349e54
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index 0f378e7..f5a4351 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -15,7 +15,7 @@
"authentication": "ON_INSTALL"
},
"category": "Developer Tools",
- "version": "0.0.197"
+ "version": "1.0.0"
}
]
}
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 704349c..f2488f8 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -9,7 +9,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.197"
+ "version": "1.0.0"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5896703..cf664cf 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.197",
+ "version": "1.0.0",
"author": {
"name": "Google Chrome"
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 56776ed..4f712e3 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "modern-web-guidance",
- "version": "0.0.197",
+ "version": "1.0.0",
"description": "Keep your coding agent up to date with the latest web best practices",
"author": {
"name": "Google Chrome",
@@ -20,7 +20,7 @@
"interface": {
"displayName": "Modern Web Guidance",
"shortDescription": "Web platform expertise",
- "longDescription": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
+ "longDescription": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
"developerName": "Google Chrome",
"category": "Developer Tools",
"composerIcon": "./assets/logo.png",
@@ -29,6 +29,9 @@
"Read"
],
"websiteURL": "https://developer.chrome.com/docs/modern-web-guidance",
+ "supportURL": "https://github.com/GoogleChrome/modern-web-guidance-src/issues",
+ "privacyPolicyURL": "https://policies.google.com/privacy",
+ "termsOfServiceURL": "https://policies.google.com/terms",
"defaultPrompt": [
"Audit this project for modern web best practices and modernization opportunities",
"What is the recommended modern way to implement responsive dialogs and popovers?"
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index 1631827..d71d7d9 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
- "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.197",
+ "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
+ "version": "1.0.0",
"author": {
"name": "Google Chrome"
}
diff --git a/.github/plugin/plugin.json b/.github/plugin/plugin.json
index 1631827..d71d7d9 100644
--- a/.github/plugin/plugin.json
+++ b/.github/plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
- "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.197",
+ "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
+ "version": "1.0.0",
"author": {
"name": "Google Chrome"
}
diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.json
index 20612a3..daef11c 100644
--- a/.grok-plugin/marketplace.json
+++ b/.grok-plugin/marketplace.json
@@ -8,7 +8,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.197"
+ "version": "1.0.0"
}
]
}
diff --git a/README.md b/README.md
index 25b5356..5d84344 100644
--- a/README.md
+++ b/README.md
@@ -6,12 +6,9 @@
[Modern Web Guidance](https://developer.chrome.com/docs/modern-web-guidance) is a set of skills that embed web platform expertise, best practices, and browser compatibility data directly into your coding agents. It helps to steer your coding agents away from legacy patterns, and instead toward solutions that harness the power and capabilities of the modern web platform.
-*Supported by the Google Chrome team, the Microsoft Edge team, and the web development community.*
+*Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, alongside the web development community.*
-> [!NOTE]
-> This is a **preview release** of Modern Web Guidance. We're actively adding new content and we [welcome contributions or feedback on GitHub](https://github.com/GoogleChrome/modern-web-guidance-src).
-
-<!-- <LIKE A DEMO VIDEO LOOP OR SOMETHING?> -->
+[Documentation](https://developer.chrome.com/docs/modern-web-guidance) · [Eval Dashboard](https://googlechrome.github.io/modern-web-guidance-src/) · [Source Code](https://github.com/GoogleChrome/modern-web-guidance-src) · [Report an Issue](https://github.com/GoogleChrome/modern-web-guidance-src/issues)
## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/terminal.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Quickstart
@@ -29,6 +26,9 @@ npx modern-web-guidance@latest search "animate a dialog modal backdrop"
# Retrieve a guide by ID
npx modern-web-guidance@latest retrieve "animate-to-from-top-layer"
+
+# Scan a codebase for legacy patterns to modernize
+npx modern-web-guidance@latest legacy-scan .
```
## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/lightbulb.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Why?
@@ -79,68 +79,72 @@ We cover the past several years of the web platform's new features, all the way
</tr>
</table>
-_View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/overlays/navigation-drawer.md).
+_View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md).
<!-- INJECT_SKILL_COVERAGE_START -->
#### The full list
<details>
-<summary><strong>232 modern web features</strong></summary>
+<summary><strong>250 modern web features</strong></summary>
-### CSS & Layout (128 features)
+### CSS & Layout (140 features)
| | | |
| :--- | :--- | :--- |
-| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) |
-| [::file-selector-button](https://web-platform-dx.github.io/web-features-explorer/features/file-selector-button/) | [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [progress()](https://web-platform-dx.github.io/web-features-explorer/features/progress-function/) |
-| [::placeholder](https://web-platform-dx.github.io/web-features-explorer/features/placeholder/) | [currentColor](https://web-platform-dx.github.io/web-features-explorer/features/currentcolor/) | [Relative colors](https://web-platform-dx.github.io/web-features-explorer/features/relative-color/) |
-| [::selection](https://web-platform-dx.github.io/web-features-explorer/features/selection/) | [Custom highlights](https://web-platform-dx.github.io/web-features-explorer/features/highlight/) | [rem](https://web-platform-dx.github.io/web-features-explorer/features/rem/) |
-| [:dir()](https://web-platform-dx.github.io/web-features-explorer/features/dir-pseudo/) | [Custom properties](https://web-platform-dx.github.io/web-features-explorer/features/custom-properties/) | [resize (CSS property)](https://web-platform-dx.github.io/web-features-explorer/features/resize/) |
-| [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/) | [display animation](https://web-platform-dx.github.io/web-features-explorer/features/display-animation/) | [revert](https://web-platform-dx.github.io/web-features-explorer/features/revert-value/) |
-| [:host-context()](https://web-platform-dx.github.io/web-features-explorer/features/host-context/) | [Element-scoped view transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions-element-scoped/) | [revert-rule](https://web-platform-dx.github.io/web-features-explorer/features/revert-rule/) |
-| [:is()](https://web-platform-dx.github.io/web-features-explorer/features/is/) | [em unit](https://web-platform-dx.github.io/web-features-explorer/features/em-unit/) | [Scroll marker target pseudo-classes](https://web-platform-dx.github.io/web-features-explorer/features/scroll-marker-targets/) |
-| [:modal](https://web-platform-dx.github.io/web-features-explorer/features/modal/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [Scroll method promises](https://web-platform-dx.github.io/web-features-explorer/features/scroll-promises/) |
-| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [filter](https://web-platform-dx.github.io/web-features-explorer/features/filter/) | [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/) |
-| [:nth-child() of &lt;selector>](https://web-platform-dx.github.io/web-features-explorer/features/nth-child-of/) | [flex-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/flexbox-flex-wrap-balance/) | [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/) |
-| [:placeholder-shown](https://web-platform-dx.github.io/web-features-explorer/features/placeholder-shown/) | [Flexbox](https://web-platform-dx.github.io/web-features-explorer/features/flexbox/) | [scroll-axis-lock](https://web-platform-dx.github.io/web-features-explorer/features/scroll-axis-lock/) |
-| [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/) | [font-size](https://web-platform-dx.github.io/web-features-explorer/features/font-size/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
-| [:where()](https://web-platform-dx.github.io/web-features-explorer/features/where/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
-| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [Forced colors](https://web-platform-dx.github.io/web-features-explorer/features/forced-colors/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
-| [@scope](https://web-platform-dx.github.io/web-features-explorer/features/scope/) | [Gradient interpolation](https://web-platform-dx.github.io/web-features-explorer/features/gradient-interpolation/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
-| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [Gradients](https://web-platform-dx.github.io/web-features-explorer/features/gradients/) | [scrollbar-gutter](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-gutter/) |
-| [@supports](https://web-platform-dx.github.io/web-features-explorer/features/supports/) | [Grid](https://web-platform-dx.github.io/web-features-explorer/features/grid/) | [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/) |
-| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [Grid lanes](https://web-platform-dx.github.io/web-features-explorer/features/grid-lanes/) | [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/) |
-| [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/) | [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
-| [Alt text for generated content](https://web-platform-dx.github.io/web-features-explorer/features/alt-text-generated-content/) | [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/) | [Shadow parts](https://web-platform-dx.github.io/web-features-explorer/features/shadow-parts/) |
-| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [inherit](https://web-platform-dx.github.io/web-features-explorer/features/inherit-value/) | [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/) |
-| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [initial](https://web-platform-dx.github.io/web-features-explorer/features/initial-value/) | [Sticky positioning](https://web-platform-dx.github.io/web-features-explorer/features/sticky-positioning/) |
-| [Animations (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/animations-css/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [Subgrid](https://web-platform-dx.github.io/web-features-explorer/features/subgrid/) |
-| [appearance](https://web-platform-dx.github.io/web-features-explorer/features/appearance/) | [isolation](https://web-platform-dx.github.io/web-features-explorer/features/isolation/) | [System colors](https://web-platform-dx.github.io/web-features-explorer/features/system-color/) |
-| [aspect-ratio](https://web-platform-dx.github.io/web-features-explorer/features/aspect-ratio/) | [Lab and LCH](https://web-platform-dx.github.io/web-features-explorer/features/lab/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
-| [at-rule()](https://web-platform-dx.github.io/web-features-explorer/features/supports-at-rule/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [text-decoration](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration/) |
-| [attr()](https://web-platform-dx.github.io/web-features-explorer/features/attr/) | [line-clamp](https://web-platform-dx.github.io/web-features-explorer/features/line-clamp/) | [text-decoration-skip-ink](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-ink/) |
-| [background-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/background-blend-mode/) | [line-height](https://web-platform-dx.github.io/web-features-explorer/features/line-height/) | [text-decoration-skip-ink: all](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-ink-all/) |
-| [background-clip: border-area](https://web-platform-dx.github.io/web-features-explorer/features/background-clip-border-area/) | [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/) | [text-decoration-skip-spaces](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-spaces/) |
-| [border-radius](https://web-platform-dx.github.io/web-features-explorer/features/border-radius/) | [Logical properties](https://web-platform-dx.github.io/web-features-explorer/features/logical-properties/) | [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/) |
-| [box-shadow](https://web-platform-dx.github.io/web-features-explorer/features/box-shadow/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/) |
-| [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/) | [min(), max(), and clamp()](https://web-platform-dx.github.io/web-features-explorer/features/min-max-clamp/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
-| [Cascade layers](https://web-platform-dx.github.io/web-features-explorer/features/cascade-layers/) | [mix-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/mix-blend-mode/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
-| [clip-path](https://web-platform-dx.github.io/web-features-explorer/features/clip-path/) | [Nesting](https://web-platform-dx.github.io/web-features-explorer/features/nesting/) | [Transitions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/transitions/) |
-| [color-mix()](https://web-platform-dx.github.io/web-features-explorer/features/color-mix/) | [Oklab and OkLCh](https://web-platform-dx.github.io/web-features-explorer/features/oklab/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
-| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [unset](https://web-platform-dx.github.io/web-features-explorer/features/unset-value/) |
-| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [overflow-wrap](https://web-platform-dx.github.io/web-features-explorer/features/overflow-wrap/) | [user-select](https://web-platform-dx.github.io/web-features-explorer/features/user-select/) |
-| [Container queries (size)](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [overflow: clip](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip/) | [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/) |
-| [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) | [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/) |
-| [Container style queries](https://web-platform-dx.github.io/web-features-explorer/features/container-style-queries/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) | [Viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-units/) |
-| [Content](https://web-platform-dx.github.io/web-features-explorer/features/content/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
-| [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) | |
+| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [progress()](https://web-platform-dx.github.io/web-features-explorer/features/progress-function/) |
+| [::details-content](https://web-platform-dx.github.io/web-features-explorer/features/details-content/) | [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [reading-flow](https://web-platform-dx.github.io/web-features-explorer/features/reading-flow/) |
+| [::file-selector-button](https://web-platform-dx.github.io/web-features-explorer/features/file-selector-button/) | [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [Relative colors](https://web-platform-dx.github.io/web-features-explorer/features/relative-color/) |
+| [::placeholder](https://web-platform-dx.github.io/web-features-explorer/features/placeholder/) | [currentColor](https://web-platform-dx.github.io/web-features-explorer/features/currentcolor/) | [rem](https://web-platform-dx.github.io/web-features-explorer/features/rem/) |
+| [::selection](https://web-platform-dx.github.io/web-features-explorer/features/selection/) | [Custom highlights](https://web-platform-dx.github.io/web-features-explorer/features/highlight/) | [resize (CSS property)](https://web-platform-dx.github.io/web-features-explorer/features/resize/) |
+| [:dir()](https://web-platform-dx.github.io/web-features-explorer/features/dir-pseudo/) | [Custom properties](https://web-platform-dx.github.io/web-features-explorer/features/custom-properties/) | [revert](https://web-platform-dx.github.io/web-features-explorer/features/revert-value/) |
+| [:focus-visible](https://web-platform-dx.github.io/web-features-explorer/features/focus-visible/) | [display animation](https://web-platform-dx.github.io/web-features-explorer/features/display-animation/) | [revert-rule](https://web-platform-dx.github.io/web-features-explorer/features/revert-rule/) |
+| [:focus-within](https://web-platform-dx.github.io/web-features-explorer/features/focus-within/) | [Element-scoped view transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions-element-scoped/) | [Safe area inset environment variables](https://web-platform-dx.github.io/web-features-explorer/features/safe-area-inset/) |
+| [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/) | [em unit](https://web-platform-dx.github.io/web-features-explorer/features/em-unit/) | [Scroll marker target pseudo-classes](https://web-platform-dx.github.io/web-features-explorer/features/scroll-marker-targets/) |
+| [:host-context()](https://web-platform-dx.github.io/web-features-explorer/features/host-context/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [Scroll method promises](https://web-platform-dx.github.io/web-features-explorer/features/scroll-promises/) |
+| [:is()](https://web-platform-dx.github.io/web-features-explorer/features/is/) | [filter](https://web-platform-dx.github.io/web-features-explorer/features/filter/) | [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/) |
+| [:modal](https://web-platform-dx.github.io/web-features-explorer/features/modal/) | [flex-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/flexbox-flex-wrap-balance/) | [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/) |
+| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [Flexbox](https://web-platform-dx.github.io/web-features-explorer/features/flexbox/) | [scroll-axis-lock](https://web-platform-dx.github.io/web-features-explorer/features/scroll-axis-lock/) |
+| [:nth-child() of &lt;selector>](https://web-platform-dx.github.io/web-features-explorer/features/nth-child-of/) | [font-size](https://web-platform-dx.github.io/web-features-explorer/features/font-size/) | [scroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/scroll-behavior/) |
+| [:placeholder-shown](https://web-platform-dx.github.io/web-features-explorer/features/placeholder-shown/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
+| [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/) | [Forced colors](https://web-platform-dx.github.io/web-features-explorer/features/forced-colors/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
+| [:where()](https://web-platform-dx.github.io/web-features-explorer/features/where/) | [Gradient interpolation](https://web-platform-dx.github.io/web-features-explorer/features/gradient-interpolation/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
+| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [Gradients](https://web-platform-dx.github.io/web-features-explorer/features/gradients/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
+| [@scope](https://web-platform-dx.github.io/web-features-explorer/features/scope/) | [Grid](https://web-platform-dx.github.io/web-features-explorer/features/grid/) | [scrollbar-gutter](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-gutter/) |
+| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [Grid lanes](https://web-platform-dx.github.io/web-features-explorer/features/grid-lanes/) | [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/) |
+| [@supports](https://web-platform-dx.github.io/web-features-explorer/features/supports/) | [Hyphenation](https://web-platform-dx.github.io/web-features-explorer/features/hyphens/) | [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/) |
+| [abs() and sign()](https://web-platform-dx.github.io/web-features-explorer/features/abs-sign/) | [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
+| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/) | [Shadow parts](https://web-platform-dx.github.io/web-features-explorer/features/shadow-parts/) |
+| [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/) | [inherit](https://web-platform-dx.github.io/web-features-explorer/features/inherit-value/) | [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/) |
+| [Alt text for generated content](https://web-platform-dx.github.io/web-features-explorer/features/alt-text-generated-content/) | [initial](https://web-platform-dx.github.io/web-features-explorer/features/initial-value/) | [Sticky positioning](https://web-platform-dx.github.io/web-features-explorer/features/sticky-positioning/) |
+| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [Interaction media queries](https://web-platform-dx.github.io/web-features-explorer/features/interaction/) | [Subgrid](https://web-platform-dx.github.io/web-features-explorer/features/subgrid/) |
+| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [System colors](https://web-platform-dx.github.io/web-features-explorer/features/system-color/) |
+| [Animations (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/animations-css/) | [isolation](https://web-platform-dx.github.io/web-features-explorer/features/isolation/) | [Text overflow](https://web-platform-dx.github.io/web-features-explorer/features/text-overflow/) |
+| [appearance](https://web-platform-dx.github.io/web-features-explorer/features/appearance/) | [Lab and LCH](https://web-platform-dx.github.io/web-features-explorer/features/lab/) | [Text stroke and fill (compatibility prefixes)](https://web-platform-dx.github.io/web-features-explorer/features/text-stroke-fill/) |
+| [aspect-ratio](https://web-platform-dx.github.io/web-features-explorer/features/aspect-ratio/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
+| [at-rule()](https://web-platform-dx.github.io/web-features-explorer/features/supports-at-rule/) | [line-clamp](https://web-platform-dx.github.io/web-features-explorer/features/line-clamp/) | [text-decoration](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration/) |
+| [attr()](https://web-platform-dx.github.io/web-features-explorer/features/attr/) | [line-height](https://web-platform-dx.github.io/web-features-explorer/features/line-height/) | [text-decoration-skip-ink](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-ink/) |
+| [background-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/background-blend-mode/) | [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/) | [text-decoration-skip-ink: all](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-ink-all/) |
+| [background-clip: border-area](https://web-platform-dx.github.io/web-features-explorer/features/background-clip-border-area/) | [Logical properties](https://web-platform-dx.github.io/web-features-explorer/features/logical-properties/) | [text-decoration-skip-spaces](https://web-platform-dx.github.io/web-features-explorer/features/text-decoration-skip-spaces/) |
+| [border-radius](https://web-platform-dx.github.io/web-features-explorer/features/border-radius/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/) |
+| [box-shadow](https://web-platform-dx.github.io/web-features-explorer/features/box-shadow/) | [min(), max(), and clamp()](https://web-platform-dx.github.io/web-features-explorer/features/min-max-clamp/) | [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/) |
+| [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/) | [mix-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/mix-blend-mode/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
+| [Cascade layers](https://web-platform-dx.github.io/web-features-explorer/features/cascade-layers/) | [Nesting](https://web-platform-dx.github.io/web-features-explorer/features/nesting/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
+| [ch unit](https://web-platform-dx.github.io/web-features-explorer/features/ch/) | [Oklab and OkLCh](https://web-platform-dx.github.io/web-features-explorer/features/oklab/) | [Transitions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/transitions/) |
+| [clip-path](https://web-platform-dx.github.io/web-features-explorer/features/clip-path/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
+| [color-mix()](https://web-platform-dx.github.io/web-features-explorer/features/color-mix/) | [overflow-wrap](https://web-platform-dx.github.io/web-features-explorer/features/overflow-wrap/) | [unset](https://web-platform-dx.github.io/web-features-explorer/features/unset-value/) |
+| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [overflow: clip](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip/) | [user-select](https://web-platform-dx.github.io/web-features-explorer/features/user-select/) |
+| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) | [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/) |
+| [Container queries (size)](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) | [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/) |
+| [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) | [Viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-units/) |
+| [Container style queries](https://web-platform-dx.github.io/web-features-explorer/features/container-style-queries/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
+| [Content](https://web-platform-dx.github.io/web-features-explorer/features/content/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) | |
### HTML & DOM (36 features)
| | | |
| :--- | :--- | :--- |
-| [:autofill](https://web-platform-dx.github.io/web-features-explorer/features/autofill/) | [&lt;slot>](https://web-platform-dx.github.io/web-features-explorer/features/slot/) | [HTML setter methods](https://web-platform-dx.github.io/web-features-explorer/features/html-setters/) |
-| [:indeterminate](https://web-platform-dx.github.io/web-features-explorer/features/indeterminate/) | [&lt;video>](https://web-platform-dx.github.io/web-features-explorer/features/video/) | [HTML streaming setters](https://web-platform-dx.github.io/web-features-explorer/features/html-streaming-setters/) |
+| [:autofill](https://web-platform-dx.github.io/web-features-explorer/features/autofill/) | [&lt;slot>](https://web-platform-dx.github.io/web-features-explorer/features/slot/) | [HTML streaming setters](https://web-platform-dx.github.io/web-features-explorer/features/html-streaming-setters/) |
+| [:indeterminate](https://web-platform-dx.github.io/web-features-explorer/features/indeterminate/) | [&lt;video>](https://web-platform-dx.github.io/web-features-explorer/features/video/) | [HTML-in-canvas](https://web-platform-dx.github.io/web-features-explorer/features/canvas-html/) |
| [&lt;audio>](https://web-platform-dx.github.io/web-features-explorer/features/audio/) | [Autonomous custom elements](https://web-platform-dx.github.io/web-features-explorer/features/autonomous-custom-elements/) | [inert](https://web-platform-dx.github.io/web-features-explorer/features/inert/) |
| [&lt;details>](https://web-platform-dx.github.io/web-features-explorer/features/details/) | [blocking="render"](https://web-platform-dx.github.io/web-features-explorer/features/blocking-render/) | [Interest invokers](https://web-platform-dx.github.io/web-features-explorer/features/interest-invokers/) |
| [&lt;dialog closedby>](https://web-platform-dx.github.io/web-features-explorer/features/dialog-closedby/) | [Customizable &lt;select>](https://web-platform-dx.github.io/web-features-explorer/features/customizable-select/) | [Invoker commands](https://web-platform-dx.github.io/web-features-explorer/features/invoker-commands/) |
@@ -150,40 +154,42 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
| [&lt;input>](https://web-platform-dx.github.io/web-features-explorer/features/input/) | [focusgroup](https://web-platform-dx.github.io/web-features-explorer/features/focusgroup/) | [Mutually exclusive &lt;details> elements](https://web-platform-dx.github.io/web-features-explorer/features/details-name/) |
| [&lt;link rel="expect">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-expect/) | [Form-associated custom elements](https://web-platform-dx.github.io/web-features-explorer/features/form-associated-custom-elements/) | [Popover](https://web-platform-dx.github.io/web-features-explorer/features/popover/) |
| [&lt;link rel="preload">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-preload/) | [hidden="until-found"](https://web-platform-dx.github.io/web-features-explorer/features/hidden-until-found/) | [popover="hint"](https://web-platform-dx.github.io/web-features-explorer/features/popover-hint/) |
-| [&lt;progress>](https://web-platform-dx.github.io/web-features-explorer/features/progress/) | [HTML in canvas](https://web-platform-dx.github.io/web-features-explorer/features/canvas-html/) | [Shadow DOM](https://web-platform-dx.github.io/web-features-explorer/features/shadow-dom/) |
+| [&lt;progress>](https://web-platform-dx.github.io/web-features-explorer/features/progress/) | [HTML setter methods](https://web-platform-dx.github.io/web-features-explorer/features/html-setters/) | [Shadow DOM](https://web-platform-dx.github.io/web-features-explorer/features/shadow-dom/) |
-### JavaScript & APIs (68 features)
+### JavaScript & APIs (74 features)
| | | |
| :--- | :--- | :--- |
-| [&lt;meta name="text-scale">](https://web-platform-dx.github.io/web-features-explorer/features/meta-text-scale/) | [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) |
-| [&lt;template for>](https://web-platform-dx.github.io/web-features-explorer/features/template-for/) | [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Small, large, and dynamic viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-unit-variants/) |
-| [AbortController and AbortSignal](https://web-platform-dx.github.io/web-features-explorer/features/aborting/) | [Keyboard events](https://web-platform-dx.github.io/web-features-explorer/features/keyboard-events/) | [Soft navigation performance entries](https://web-platform-dx.github.io/web-features-explorer/features/soft-navigations/) |
-| [ARIA attribute reflection](https://web-platform-dx.github.io/web-features-explorer/features/aria-attribute-reflection/) | [Language detector](https://web-platform-dx.github.io/web-features-explorer/features/languagedetector/) | [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/) |
-| [autocorrect](https://web-platform-dx.github.io/web-features-explorer/features/autocorrect/) | [LanguageModel](https://web-platform-dx.github.io/web-features-explorer/features/languagemodel/) | [Subresource integrity](https://web-platform-dx.github.io/web-features-explorer/features/subresource-integrity/) |
-| [border-shape](https://web-platform-dx.github.io/web-features-explorer/features/border-shape/) | [Lazy-loading images and iframes](https://web-platform-dx.github.io/web-features-explorer/features/loading-lazy/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
-| [Connection allowlists](https://web-platform-dx.github.io/web-features-explorer/features/connection-allowlists/) | [light-dark() image values](https://web-platform-dx.github.io/web-features-explorer/features/light-dark-image/) | [SVG](https://web-platform-dx.github.io/web-features-explorer/features/svg/) |
-| [corner-shape](https://web-platform-dx.github.io/web-features-explorer/features/corner-shape/) | [Local network access](https://web-platform-dx.github.io/web-features-explorer/features/local-network-access/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
-| [Credential management](https://web-platform-dx.github.io/web-features-explorer/features/credential-management/) | [Long animation frames performance entries](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/) | [text-decoration-inset](https://web-platform-dx.github.io/web-features-explorer/features/tmp-text-decoration-inset/) |
-| [cross-origin() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-cross-origin/) | [long-animation-frames-style-layout](https://web-platform-dx.github.io/web-features-explorer/features/tmp-long-animation-frames-style-layout/) | [text-fit](https://web-platform-dx.github.io/web-features-explorer/features/text-fit/) |
-| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/) | [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/) |
-| [email-verification](https://web-platform-dx.github.io/web-features-explorer/features/tmp-email-verification/) | [Origin](https://web-platform-dx.github.io/web-features-explorer/features/origin/) | [touch-action](https://web-platform-dx.github.io/web-features-explorer/features/touch-action/) |
-| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/) | [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/) |
-| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [Page visibility state performance entries](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/) | [Trusted types](https://web-platform-dx.github.io/web-features-explorer/features/trusted-types/) |
-| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [Partitioned cookies](https://web-platform-dx.github.io/web-features-explorer/features/partitioned-cookies/) | [User agent client hints](https://web-platform-dx.github.io/web-features-explorer/features/ua-client-hints/) |
-| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [Password credentials](https://web-platform-dx.github.io/web-features-explorer/features/password-credentials/) | [Web app origin migration](https://web-platform-dx.github.io/web-features-explorer/features/app-migration/) |
-| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [Permissions policy](https://web-platform-dx.github.io/web-features-explorer/features/permissions-policy/) | [Web authentication](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
-| [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/) | [Pointer Events](https://web-platform-dx.github.io/web-features-explorer/features/pointer-events-api/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
-| [HTML processing instructions](https://web-platform-dx.github.io/web-features-explorer/features/html-processing-instructions/) | [Referrer policy](https://web-platform-dx.github.io/web-features-explorer/features/referrer-policy/) | [Web Cryptography](https://web-platform-dx.github.io/web-features-explorer/features/web-cryptography/) |
-| [image()](https://web-platform-dx.github.io/web-features-explorer/features/image-function/) | [referrer-policy() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-referrer-policy/) | [WebAssembly](https://web-platform-dx.github.io/web-features-explorer/features/wasm/) |
-| [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/) | [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/) | [webcrypto-modern-algos](https://web-platform-dx.github.io/web-features-explorer/features/tmp-webcrypto-modern-algos/) |
-| [integrity() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-integrity/) | [Resize observer](https://web-platform-dx.github.io/web-features-explorer/features/resize-observer/) | [WebOTP](https://web-platform-dx.github.io/web-features-explorer/features/web-otp/) |
-| [Interaction contentful paint performance entries](https://web-platform-dx.github.io/web-features-explorer/features/interaction-contentful-paint/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) | |
+| [&lt;install>](https://web-platform-dx.github.io/web-features-explorer/features/install/) | [integrity() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-integrity/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) |
+| [&lt;meta name="text-scale">](https://web-platform-dx.github.io/web-features-explorer/features/meta-text-scale/) | [Interaction contentful paint performance entries](https://web-platform-dx.github.io/web-features-explorer/features/interaction-contentful-paint/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) |
+| [&lt;template for>](https://web-platform-dx.github.io/web-features-explorer/features/template-for/) | [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Small, large, and dynamic viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-unit-variants/) |
+| [AbortController and AbortSignal](https://web-platform-dx.github.io/web-features-explorer/features/aborting/) | [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Soft navigation performance entries](https://web-platform-dx.github.io/web-features-explorer/features/soft-navigations/) |
+| [ARIA attribute reflection](https://web-platform-dx.github.io/web-features-explorer/features/aria-attribute-reflection/) | [Keyboard events](https://web-platform-dx.github.io/web-features-explorer/features/keyboard-events/) | [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/) |
+| [ariaNotify()](https://web-platform-dx.github.io/web-features-explorer/features/arianotify/) | [Language detector](https://web-platform-dx.github.io/web-features-explorer/features/languagedetector/) | [Subresource integrity](https://web-platform-dx.github.io/web-features-explorer/features/subresource-integrity/) |
+| [Async clipboard](https://web-platform-dx.github.io/web-features-explorer/features/async-clipboard/) | [LanguageModel](https://web-platform-dx.github.io/web-features-explorer/features/languagemodel/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
+| [autocorrect](https://web-platform-dx.github.io/web-features-explorer/features/autocorrect/) | [Lazy-loading images and iframes](https://web-platform-dx.github.io/web-features-explorer/features/loading-lazy/) | [SVG](https://web-platform-dx.github.io/web-features-explorer/features/svg/) |
+| [beforeinstallprompt](https://web-platform-dx.github.io/web-features-explorer/features/beforeinstallprompt/) | [light-dark() image values](https://web-platform-dx.github.io/web-features-explorer/features/light-dark-image/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
+| [border-shape](https://web-platform-dx.github.io/web-features-explorer/features/border-shape/) | [Local network access](https://web-platform-dx.github.io/web-features-explorer/features/local-network-access/) | [text-decoration-inset](https://web-platform-dx.github.io/web-features-explorer/features/tmp-text-decoration-inset/) |
+| [Connection allowlists](https://web-platform-dx.github.io/web-features-explorer/features/connection-allowlists/) | [Long animation frames performance entries](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/) | [text-fit](https://web-platform-dx.github.io/web-features-explorer/features/text-fit/) |
+| [corner-shape](https://web-platform-dx.github.io/web-features-explorer/features/corner-shape/) | [long-animation-frames-style-layout](https://web-platform-dx.github.io/web-features-explorer/features/tmp-long-animation-frames-style-layout/) | [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/) |
+| [Credential management](https://web-platform-dx.github.io/web-features-explorer/features/credential-management/) | [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/) | [touch-action](https://web-platform-dx.github.io/web-features-explorer/features/touch-action/) |
+| [cross-origin() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-cross-origin/) | [navigator.install()](https://web-platform-dx.github.io/web-features-explorer/features/navigator-install/) | [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/) |
+| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [Origin](https://web-platform-dx.github.io/web-features-explorer/features/origin/) | [Trusted types](https://web-platform-dx.github.io/web-features-explorer/features/trusted-types/) |
+| [email-verification](https://web-platform-dx.github.io/web-features-explorer/features/tmp-email-verification/) | [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/) | [User agent client hints](https://web-platform-dx.github.io/web-features-explorer/features/ua-client-hints/) |
+| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [Page visibility state performance entries](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/) | [Web app manifest](https://web-platform-dx.github.io/web-features-explorer/features/manifest/) |
+| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [Partitioned cookies](https://web-platform-dx.github.io/web-features-explorer/features/partitioned-cookies/) | [Web app origin migration](https://web-platform-dx.github.io/web-features-explorer/features/app-migration/) |
+| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [Password credentials](https://web-platform-dx.github.io/web-features-explorer/features/password-credentials/) | [Web authentication](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
+| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [Permissions policy](https://web-platform-dx.github.io/web-features-explorer/features/permissions-policy/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
+| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [Pointer Events](https://web-platform-dx.github.io/web-features-explorer/features/pointer-events-api/) | [Web Cryptography](https://web-platform-dx.github.io/web-features-explorer/features/web-cryptography/) |
+| [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/) | [Referrer policy](https://web-platform-dx.github.io/web-features-explorer/features/referrer-policy/) | [WebAssembly](https://web-platform-dx.github.io/web-features-explorer/features/wasm/) |
+| [HTML processing instructions](https://web-platform-dx.github.io/web-features-explorer/features/html-processing-instructions/) | [referrer-policy() for url()](https://web-platform-dx.github.io/web-features-explorer/features/url-referrer-policy/) | [webcrypto-modern-algos](https://web-platform-dx.github.io/web-features-explorer/features/tmp-webcrypto-modern-algos/) |
+| [image()](https://web-platform-dx.github.io/web-features-explorer/features/image-function/) | [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/) | [WebOTP](https://web-platform-dx.github.io/web-features-explorer/features/web-otp/) |
+| [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/) | [Resize observer](https://web-platform-dx.github.io/web-features-explorer/features/resize-observer/) | |
</details>
<details>
-<summary><strong>188 real-world developer use cases</strong></summary>
+<summary><strong>203 real-world developer use cases</strong></summary>
<h3>accessibility</h3>
@@ -223,7 +229,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[animated-select-picker](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/animated-select-picker.md)**: Create a custom select component whose dropdown is animated. For example, the menu fades or slides into view, or the options animate upon selection.
- **[autofill-address-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-address-form.md)**: Build an address form with correct autocomplete attributes and autofill support.
-- **[autofill-highlight-inputs](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md)**: Use CSS to highlight form fields that have been autofilled by the browser and not edited by the user.
+- **[autofill-highlight-inputs](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md)**: Customize the styling of form fields that have been autofilled and not edited by the user
- **[autofill-payment-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-payment-form.md)**: Build a payment form that collects card details with correct autocomplete values and autofill support.
- **[autofill-sign-in-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md)**: Build a sign-in form with correct autocomplete values and autofill support.
- **[autofill-sign-up-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md)**: Build a sign-up form with correct autocomplete values and autofill support.
@@ -261,7 +267,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
<h3>performance</h3>
- **[batch-analytics-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/batch-analytics-events.md)**: Debounce and batch multiple analytics, telemetry, and Core Web Vitals events together in a single beacon to minimize network contention and reduce server load, while still delivering real-time updates.
-- **[break-up-long-tasks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md)**: Break up heavy synchronous processing (complex computations and/or long loops) or DOM updates, to let the browser handle user input and repaint the screen.
+- **[break-up-long-tasks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md)**: Break up heavy synchronous processing (complex computations and/or long loops) or DOM updates to improve Interaction to Next Paint (INP) responsiveness and let the browser handle user input and repaint the screen.
- **[calculate-total-foreground-time](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/calculate-total-foreground-time.md)**: Calculate the total time a user actually spent viewing a page, excluding periods when the tab was in the background.
- **[conditional-async-dependencies](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/conditional-async-dependencies.md)**: Conditionally load or initialize async dependencies (such as importing polyfills for missing web features) without requiring complex orchestration across all of a page's script dependencies.
- **[defer-rendering-heavy-content](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/defer-rendering-heavy-content.md)**: Reduce rendering times in content-heavy web pages (e.g. pages with long feeds, lots of articles, or complex dashboards), by deferring rendering for any content that is not immediately visible to the user.
@@ -292,6 +298,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
<h3>pwa</h3>
+- **[install-web-app](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/pwa/install-web-app.md)**: Install web applications from a page using browser-controlled consent UI.
- **[migrate-web-app-origin](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md)**: Transfer an installed web app to a new origin while preserving user configuration and OS-level shortcuts.
<h3>security</h3>
@@ -323,8 +330,9 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[responsive-table](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md)**: Build a data table that presents tabular data with proper header semantics, and remains readable and navigable on small screens and with assistive technologies.
- **[scroll-position-aware-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md)**: Build floating buttons or widgets (back-to-top, scroll-to-bottom, chat launchers, etc.) that appear and disappear based on whether the user has scrolled at all.
- **[scroll-progress-indicator](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md)**: Create a scroll progress bar, stepped progress tracker, or any visual affordance that communicates how far through a page or section the user has scrolled.
-- **[scrollability-affordance-hints](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md)**: Build scroll-shadow overlays, gradient fades, or directional arrow indicators that appear only when there's actually more content to scroll to in that direction.
+- **[scrollability-affordance-hints](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md)**: Build scroll shadows or fading edges that appear only when there's actually more content to scroll to in that direction.
- **[shrinking-header-on-scroll](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md)**: Smoothly animate a fixed header or full-page cover on scroll to dynamically shrink, gain shadows, and transform its layout over a predefined scroll distance.
+- **[single-line-overflow](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/single-line-overflow.md)**: Show text that must stay on one line, such as a tab label, table cell, navigation item, or file name, in a space it may not fit, without breaking the layout or losing the text.
- **[state-aware-sticky-headers](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md)**: Build sticky section headers or navbars that visually transform when they're actually "stuck" at the top, changing their color scheme or gaining a shadow.
- **[viewport-aware-dropdowns](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md)**: Position dropdowns, flyouts, or contextual action panels tethered to a trigger button so they automatically flip axes at viewport edges instead of getting clipped.
@@ -341,8 +349,10 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[declarative-dialog-popover-control](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md)**: Toggle the visibility of a dialog or popover from a button without writing JavaScript.
- **[directional-navigation-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/directional-navigation-transitions.md)**: Animate visual state changes to reflect the direction of a user's navigational flow, such as sliding new content in from the right when advancing forward or from the left when returning to a previous screen.
- **[drag](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/drag.md)**: Support dragging to move a floating element around the page.
+- **[drag-and-drop](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/drag-and-drop.md)**: Support dragging to rearrange the children of a container along one axis (horizontal or vertical) while preserving their state and accessible order.
- **[dynamic-sibling-animations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/dynamic-sibling-animations.md)**: Stagger animation or transition timing across sibling elements so each one starts after a computed delay based on its position in the sibling list.
-- **[group-element-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md)**: Transition a group of similar elements simultaneously using the same transition logic, such as removing a product from a shopping cart and having all the other products animate into their new positions.
+- **[dynamic-sort](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/dynamic-sort.md)**: Best practices for handling dynamic user-triggered reordering of a container's children (e.g. list items, table rows, or a card grid), with optional animated reordering that respects user preferences, good screen reader UX, and optimal performance for large lists.
+- **[group-element-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md)**: Smoothly rearrange and animate list items, cards, or grid elements into their new positions simultaneously when adding, removing, shuffling, or reordering—such as removing a product from a shopping cart.
- **[highlight-text-ranges](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/highlight-text-ranges.md)**: Highlight arbitrary text ranges on a page such as search results, spelling errors, or collaborative editing cursors.
- **[interactive-content-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/interactive-content-reveal.md)**: Create interactive reveal effects, such as a spotlight that follows the user's pointer to uncover details within an image or UI section.
- **[interest-triggered-action-previews](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-action-previews.md)**: Show a live preview of a button's effect when a user signals interest (e.g. hovering, focusing, or long-pressing) but before they commit to clicking.
@@ -364,18 +374,25 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[scroll-target-on-load](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scroll-target-on-load.md)**: Build a scrollable list of elements (e.g. a carousel of images or a chat conversation thread) that can be displayed with a particular element scrolled into view on the initial render.
- **[scrollytelling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md)**: Animate visual properties on a target element — such as fading a backdrop, shifting a background color, or to create scrollytelling experiences — driven entirely by the scrollport position of a completely different element.
- **[search-hidden-content](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/search-hidden-content.md)**: Hide content from view using patterns such as accordions, tabs, and "Read more" sections, while ensuring the hidden text reveals itself during native "Find in page" searches, allows search engine indexing, supports URL fragment deep links, and maintains ARIA accessibility.
+- **[sortable-table](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/sortable-table.md)**: Progressively enhance a data table with behaviors that allow users to sort rows by clicking on column headers.
- **[spatial-navigation](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md)**: Implement accessible spatial navigation using arrow keys that works correctly in different layout modes (grid etc)
- **[swipe-to-remove](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md)**: Let users act on items in a list (remove, archive, mark as read, etc.) with a horizontal swipe gesture, so they can process entries quickly without tapping a separate control.
- **[swipe-to-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-reveal.md)**: Let users swipe horizontally on a list item or content pane to reveal contextual action buttons or a side menu without automatically triggering an action.
<h3>ui-components</h3>
+- **[accordion](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/accordion.md)**: Build an accordion component with animation, optional exclusive (one-open-at-a-time) behavior, and brand-consistent styling.
+- **[app-menus](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/app-menus.md)**: Build an application menu bar where several top-level menus (such as File, Edit, and View) act as a single keyboard stop and switch between each other on hover or arrow keys.
+- **[breadcrumbs](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/breadcrumbs.md)**: Build a breadcrumb trail that shows the user's location within a site hierarchy and lets them navigate to ancestor pages.
- **[card](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/card.md)**: Build a card component that adapts its presentation to its own available space and contents.
+- **[carousel](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/carousel.md)**: Build a carousel component that displays a set of items in a horizontal or vertical layout.
- **[checkbox](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/checkbox.md)**: Style checkboxes, including custom icons, layout, colors, check/uncheck animations, while preserving native functionality and accessibility.
+- **[copy-button](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/copy-button.md)**: Build a copy button that copies text from arbitrary elements to the clipboard.
- **[dark-mode-toggle](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/dark-mode-toggle.md)**: Build a dark mode toggle component that allows users to override their system color scheme preference for the current site.
- **[dialog](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/dialog.md)**: Build a modal or non-modal dialog component that is accessible, manages focus appropriately, and can be dismissed the way users expect on each platform.
- **[hovercard](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/hovercard.md)**: Build a hovercard component that displays an interactive structured preview of the page a certain type of link (e.g. a user profile) will navigate to when hovered over.
- **[menu](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/menu.md)**: Build a menu component that displays a list of options or actions, with support for nested submenus.
+- **[navbar](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/navbar.md)**: Build a site navigation bar that adapts across screen sizes and indicates the current page.
- **[navigation-drawer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md)**: Create a navigation drawer component that, when triggered from a menu button, slides in from the side overlaid on top of existing page content, and slides out when dismissed (by swiping away, tapping outside, or pressing escape).
- **[persistent-app-tours](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md)**: Create persistent onboarding walkthroughs using tethered native overlays that stay open during user interaction.
- **[persistent-toast-notifications](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md)**: Create non-intrusive toast and overlay notifications for persistent, stackable messaging and state communication.
@@ -384,10 +401,14 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[scrollspy](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/scrollspy.md)**: Highlight the currently visible section of a page in a navigation menu
- **[spinner](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/spinner.md)**: Build a loading spinner that communicates busy state to all users, respects reduced-motion preferences, and animates efficiently.
- **[stack-drill-down](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/stack-drill-down.md)**: Build full-screen hierarchical navigation that lets users drill down into nested views and swipe or navigate back to return, with browser history kept in sync.
+- **[tabs](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/tabs.md)**: Build a responsive tabbed interface with good UX when not all tabs fit on screen.
+- **[toolbar](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/toolbar.md)**: Build a toolbar component that displays a set of controls for performing actions.
<h3>user-experience</h3>
- **[content-first-noise-reduction](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/content-first-noise-reduction.md)**: Maximize content and reduce noise by removing blocking popups, keeping persistent navigation compact, and moving secondary content behind on-demand disclosure.
+- **[form-factor-adaptation](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/form-factor-adaptation.md)**: Adapt layouts, controls, and text to any device or container so touch targets stay usable, content fits its space, and nothing collides with system UI.
+- **[natural-interactions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/natural-interactions.md)**: Implement natural interactions with clear hover, focus, and press feedback, motion that opens from its trigger, swipeable content, and keyboard-reachable actions.
<h3>visual-design</h3>
@@ -431,13 +452,22 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
* **Progressive Enhancement & Nuanced Fallbacks**: We distinguish between purely additive enhancements (like speculative preloading) which are safe to let older browsers silently ignore, and critical behaviors (like dialog controls or network beacons) where we write highly considered, low-overhead fallbacks.
* **Responsible Fallbacks**: We prioritize lightweight, case-specific custom fallbacks (<50 LOC) or conditionally-loaded polyfills instead of heavy third-party bundles.
* **Gotchas & Quirks**: We document hidden platform limitations, such as the 64KB payload quota for `fetchLater()` or macOS-specific scrollbar behaviors.
-* **Baseline-Aware Integration**: We leverage real-time compatibility data from the **Baseline** project so agents can dynamically adapt to current browser support and any browser support preferences.
-* **Origin Trial Opt-In Gate**: Guides for experimental Origin Trial APIs are discoverable via search, but gated on `retrieve` so agents do not adopt unstable APIs without consent. Run `npx modern-web-guidance@latest set-allow-origin-trials` in your terminal to opt a project in (writes `{"allowOriginTrials": true}` to `.mwgrc`; set to `false` or delete `.mwgrc` to opt out).
+* **Baseline-Aware Integration**: We leverage real-time compatibility data from the **Baseline** project so agents dynamically adapt to current browser support.
+* **Origin Trial & Volatile Feature Gates**: Guides covering experimental **Origin Trial** APIs or **volatile features** (single-engine features shipped within the last 3 months or still stabilizing) remain discoverable via `search`, but are gated on `retrieve` so agents do not adopt unstable APIs without explicit developer consent.
+
+### Project Configuration (`.mwgrc`)
+
+Configure Origin Trial and volatile feature opt-ins for a repository with an optional `.mwgrc` JSON file in your project root (or `~/.mwgrc` as a user-level fallback), which you can commit to share across your team:
+
+| CLI Command | `.mwgrc` Key | Effect |
+| :--- | :--- | :--- |
+| `npx modern-web-guidance@latest set-allow-origin-trials` | `"allowOriginTrials": true` | Unlocks guides for experimental Origin Trial APIs. |
+| `npx modern-web-guidance@latest set-allow-volatile-features` | `"allowVolatileFeatures": true` | Unlocks guides for volatile single-engine features. |
## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/cpu.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> How It Works
1. **Activation**: The coding agent activates the `modern-web-guidance` skill because of a relevant task. The agent is instructed to use the `modern-web-guidance` CLI for web platform queries.
-2. **Local Semantic Search**: The agent runs `modern-web-guidance search "<query>"`. The tool matches the query to the best guide using an offline, CPU-efficient TensorFlow.js model (no network calls, no API keys).
+2. **Local Semantic Search**: The agent runs `modern-web-guidance search "<query>"`. The tool matches the query to the best guide using an offline, zero-dependency embedding model and BM25 search engine (no network calls, no API keys).
3. **Guide Fetch**: The agent retrieves the guide via `modern-web-guidance retrieve <guide-id>`, inserting targeted code patterns, gotchas, and fallbacks directly into its context window.
> [!TIP]
@@ -521,44 +551,46 @@ If you installed the skill using `npx modern-web-guidance@latest install`, you c
Otherwise, consult your agent's documentation for updating plugins and skills.
-## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/shield-check.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Evals to prove this works well ;)
+## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/shield-check.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Evals to prove this works well
-We developed a robust eval harness to ensure that the content is **empirically proven and continuously calibrated** to ensure AI agents write better code. We run automated evaluations using a closed-loop validation pipeline:
+We developed a robust eval harness to ensure that the content is **empirically proven and continuously calibrated** so AI agents write better code. We run automated evaluations using a closed-loop validation pipeline:
```
[ Expert-authored guidance and demo ]
│
▼
- [ Generated assets ] ──> Playwright Grader (.spec.ts) & Negative Demo (.html)
+ [ Target generation ] ──> Tasks on real webapps, Golden solutions, Playwright graders
│
▼
- [ Calibration loop ] ───────> Runs Grader on Gold-Standard Demo (Must Pass 100%)
- │ Runs Grader on Negative Demo (Must Fail 100%)
+ [ Calibration loop ] ───> Runs Grader on Golden Solutions (Must Pass 100%)
+ │ Runs Grader on Unmodified Base App (Must Fail 100%)
▼
- [ E2E agent evals ] ────────> Runs coding agents in guided vs. unguided modes
- Compares accuracy w/ and w/o the skill
+ [ E2E agent evals ] ────> Runs coding agents in guided vs. unguided modes
+ Compares pass rates and accessibility w/ and w/o the skill
```
-0. **Simulated Developer Tasks**: We define realistic, developer prompts that mimic real-world requests (e.g., "make my images load faster"). The prompts avoid naming APIs or features, testing whether the agent can successfully discover the relevant guides naturally.
-1. **Browser-based Assertions**: We write browser automation scripts that verify the guide was followed correctly: exact runtime behaviors, computed styles, accessibility states, etc.
-2. **Self-Healing Calibration**: Graders are calibrated against both a reference implementation (100% pass target) and a control page (0% pass target). The agent automatically refines tests on failure.
-3. **E2E Testing**: We measure coding agent performance on real tasks with and without guidance. The _opportunity_ (100% - unguided pass rate) and _uplift_ (guided - unguided pass rate) are key. If there's little opportunity, then models already do a great job and our guidance isn't providing much value. Based on the results, we revise guides to maximize the uplift, optimizing their effectiveness.
+1. **Simulated Developer Tasks**: We define realistic developer prompts against full base applications (`daily-grind`, `devtools-times`) that mimic real-world requests (e.g., "make my images load faster"). Prompts avoid naming APIs or features, testing whether the agent can naturally discover and apply the right guides.
+2. **Static & Browser-Based Assertions**: Playwright graders verify that each implementation requirement was followed—checking source patterns, computed styles, runtime DOM behaviors, and accessibility states.
+3. **Self-Healing Calibration**: Graders are calibrated against multi-agent (Claude/Codex/AGY) golden solutions (100% pass target) and an unmodified baseline application (0% pass target).
+4. **E2E Testing**: We measure coding agent performance on real tasks with and without guidance. The _opportunity_ (100% - unguided pass rate) and _uplift_ (guided - unguided pass rate) are key: if models already succeed without guidance, we prune redundant advice; where agents struggle, we refine guides to maximize uplift.
### Recent eval results snapshot
+Explore full per-agent and per-guide breakdowns on the **[Eval Dashboard](https://googlechrome.github.io/modern-web-guidance-src/)**.
+
<!-- INJECT_EVAL_RESULTS_START -->
| Date | Agent + Model | Tasks / Assertions | Unguided → Guided (Uplift) |
| :--- | :--- | :---: | :---: |
+| Nov 8 | antigravity_cli (gemini-4-argon) | 214 / 1673 | 58% → 94% (**+36pp**) |
+| Nov 8 | codex_cli (gpt-6.1-sol) | 215 / 1795 | 54% → 82% (**+28pp**) |
+| Nov 8 | claude_code (opus-5-5) | 215 / 1801 | 57% → 88% (**+31pp**) |
+| Nov 6 | codex_cli (gpt-6.1-sol) | 212 / 1773 | 53% → 86% (**+33pp**) |
+| Nov 6 | claude_code (opus-5-5) | 212 / 1773 | 56% → 90% (**+34pp**) |
+| Nov 6 | antigravity_cli (gemini-4-argon) | 212 / 1722 | 60% → 96% (**+36pp**) |
+| Nov 4 | codex_cli (gpt-6.1-sol) | 209 / 1743 | 52% → 85% (**+33pp**) |
+| Nov 4 | claude_code (opus-5-5) | 209 / 1743 | 57% → 90% (**+33pp**) |
+| Nov 4 | antigravity_cli (gemini-4-argon) | 207 / 1722 | 60% → 96% (**+36pp**) |
| Nov 2 | codex_cli (gpt-6.1-sol) | 205 / 1729 | 55% → 82% (**+27pp**) |
-| Nov 2 | claude_code (opus-5-5) | 205 / 1729 | 58% → 90% (**+32pp**) |
-| Nov 1 | antigravity_cli (gemini-4-argon) | 205 / 1705 | 61% → 96% (**+35pp**) |
-| Oct 30 | codex_cli (gpt-6.1-sol) | 204 / 1721 | 55% → 84% (**+29pp**) |
-| Oct 30 | claude_code (opus-5-5) | 204 / 1721 | 58% → 91% (**+33pp**) |
-| Oct 30 | antigravity_cli (gemini-4-argon) | 204 / 1637 | 61% → 96% (**+35pp**) |
-| Oct 28 | codex_cli (gpt-6.1-sol) | 198 / 1675 | 56% → 85% (**+29pp**) |
-| Oct 28 | claude_code (fable-5-1) | 198 / 1646 | 54% → 90% (**+36pp**) |
-| Oct 28 | antigravity_cli (gemini-4-argon) | 197 / 1629 | 60% → 95% (**+35pp**) |
-| Oct 25 | claude_code (sonnet-5-5) | 168 / 1422 | 56% → 90% (**+34pp**) |
<!-- INJECT_EVAL_RESULTS_END -->
@@ -570,8 +602,8 @@ You can customize which skill packs are installed using the `--choose` flag:
npx modern-web-guidance@latest install --choose
```
-* **`modern-web-guidance`** (~234 tokens): Comprehensive guidance on modern browser APIs, layouts, and performance.
-* **`chrome-extensions`** (~181 tokens): Guidance on Manifest V3, background workers, extension APIs, and Chrome Web Store publishing.
+* **`modern-web-guidance`** (~205 tokens): Comprehensive guidance on modern browser APIs, layouts, and performance.
+* **`chrome-extensions`** (~175 tokens): Guidance on Manifest V3, background workers, extension APIs, and Chrome Web Store publishing.
## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/lock.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Telemetry & Privacy
@@ -587,7 +619,7 @@ Google handles this data in accordance with the [Google Privacy Policy](https://
## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/users.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Contributors
-If you'd like to contribute to modern-web-guidance, please see the [source repo's `CONTRIBUTING.md`](https://github.com/GoogleChrome/modern-web-guidance-src/blob/main/CONTRIBUTING.md). The `modern-web-guidance` repo is purely a publish target for clean skills installation.
+Found a bug, outdated pattern, or missing web platform feature? [Open an issue](https://github.com/GoogleChrome/modern-web-guidance-src/issues) or see [`CONTRIBUTING.md`](https://github.com/GoogleChrome/modern-web-guidance-src/blob/main/CONTRIBUTING.md) in the [source repository (`GoogleChrome/modern-web-guidance-src`)](https://github.com/GoogleChrome/modern-web-guidance-src).
Huge thanks to everyone who has contributed!
@@ -595,6 +627,10 @@ Huge thanks to everyone who has contributed!
<img src="https://contrib.rocks/image?repo=GoogleChrome/modern-web-guidance-src&max=101" />
</a>
-## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/file-text.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> Attribution
+## <img src="https://github.com/GoogleChrome/modern-web-guidance/raw/main/.github/img/file-text.svg" width="24" height="24" style="vertical-align: middle; margin-right: 4px;"> License
+
+Unless otherwise noted:
+* Software code in this project is licensed under the [Apache License 2.0](https://github.com/GoogleChrome/modern-web-guidance-src/blob/main/LICENSE).
+* Documentation and guide content under `guides/` are licensed under [Creative Commons Attribution 4.0 International (CC-BY 4.0)](https://creativecommons.org/licenses/by/4.0/).
Portions of the documentation in this project are derived from [MDN Web Docs](https://developer.mozilla.org/) by Mozilla Contributors and [W3C](https://www.w3.org/), [WHATWG](https://whatwg.org), and [IETF](https://www.ietf.org) specifications.
diff --git a/gemini-extension.json b/gemini-extension.json
index 5896703..cf664cf 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.197",
+ "version": "1.0.0",
"author": {
"name": "Google Chrome"
}
diff --git a/kimi.plugin.json b/kimi.plugin.json
index 38537cc..b21be64 100644
--- a/kimi.plugin.json
+++ b/kimi.plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
- "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.197",
+ "description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
+ "version": "1.0.0",
"author": {
"name": "Google Chrome"
},
diff --git a/package.json b/package.json
index b4e785f..5060b3b 100644
--- a/package.json
+++ b/package.json
@@ -3,10 +3,15 @@
"displayName": "Modern Web Guidance",
"description": "Keep your agent up to date on the latest web best practices.",
"license": "Apache-2.0",
- "version": "0.0.197",
+ "version": "1.0.0",
"publisher": "GoogleChrome",
+ "homepage": "https://developer.chrome.com/docs/modern-web-guidance",
"repository": {
- "url": "https://github.com/GoogleChrome/modern-web-guidance-src"
+ "type": "git",
+ "url": "https://github.com/GoogleChrome/modern-web-guidance-src.git"
+ },
+ "bugs": {
+ "url": "https://github.com/GoogleChrome/modern-web-guidance-src/issues"
},
"engines": {
"vscode": "^1.90.0",
diff --git a/plugin.json b/plugin.json
index 57ee48f..843c9ce 100644
--- a/plugin.json
+++ b/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "modern-web-guidance",
- "version": "0.0.197",
+ "version": "1.0.0",
"description": "Keep your coding agent up to date with the latest web best practices",
"author": {
"name": "Google Chrome",
diff --git a/skills/modern-web-guidance/SKILL.md b/skills/modern-web-guidance/SKILL.md
index 6aabbe7..fdab1a7 100644
--- a/skills/modern-web-guidance/SKILL.md
+++ b/skills/modern-web-guidance/SKILL.md
@@ -10,22 +10,23 @@ description: |
Search and retrieve standardized modern web best practices at the **start** of implementing or updating any web UI, CSS layout/animation, or client-side JS logic (dates/timezones, sanitization, performance, accessibility, UX fixes) before writing ad-hoc solutions or adding dependencies.
-## Usage Instructions
+## Primary Workflow
### Step 1. Search Use Cases
Run `modern-web-guidance` directly with `npx` using a **2–5 word action-oriented query** for a **single web platform capability or UI pattern**:
- **Keep queries focused and generic**: Describe the user-visible capability (`<verb> + <UI/platform object>`, optionally paired with the target HTML/CSS/JS feature name if known). Omit framework/library names (`React`, `Vue`, `Tailwind`, etc.) and app/domain nouns (product, route, or component/file names). Split multi-feature tasks into separate `search` calls.
+- **Name implied UI primitives**: When the user's prompt expresses intent without naming the UI primitive (e.g. "confirm first", "delete with confirmation", "pick a date"), translate the domain intent into the implied UI component or platform mechanism (e.g. search `"confirmation modal dialog"` or `"confirm dialog"` rather than `"confirm destructive action"`, or `"date picker input"` rather than `"pick a date"`).
- **Example**: Search `"light dismiss dialog"` or `"responsive data table"`, **not** `"dialog"` (too terse), `"responsive table dark mode"` (compound — split into two searches), or `"close React settings modal on outside click"` (framework/app noise).
```sh
-npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_10_30-58d055df
+npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_11_09-5bcc021b
```
> **Note**: Returns `[{ "id", "description" }, ...]`. Judge results by their `description` fields:
> - **Match found**: Call `retrieve` directly—do not also run `list`.
-> - **No match on a web UI/CSS/DOM behavior (or broad UI audit)**: If `search` returns `[]` or unrelated descriptions because your phrasing differed from the catalog (or your task spans multiple categories), run `npx -y modern-web-guidance@latest list` once to check if the pattern is covered under more general terminology.
-> - **Topic not covered**: If no guide `description` directly matches your task, proceed with your implementation without retry loops or retrieving unrelated guides.
+> - **Weak or empty results**: If `search` returns `[]` or unrelated descriptions, **rephrase `search` once** using the concrete HTML/CSS/UI component noun or synonym (e.g., `dialog`, `modal`, `popover`, `table`, `form`) before falling back to `list` (or use `list` once for broad UI audits).
+> - **Topic not covered**: If no `description` matches after rephrasing, proceed without retrieving unrelated guides.
### Step 2. Retrieve Best Practices
@@ -42,6 +43,7 @@ If `retrieve` saves large output (> 9.5 KB) to a temporary file to prevent trunc
When generating or modifying code, cross-check the implementation against the retrieved guide before concluding:
- **Applicable Guidance & Fallbacks**: Ensure the relevant modern patterns and necessary fallback strategies from the guide are correctly applied, without forcing unrequested features.
- **Task Fulfillment**: Confirm that the implementation fully satisfies the user's request.
+- Do not run `legacy-scan`; it's for detecting legacy patterns to modernize, not this.
### Step 4. Disclose Skill Usage
@@ -51,6 +53,22 @@ When you consult `modern-web-guidance` for a task, end the response where you de
- **Never** guess `<id>`s or quotes from memory after context compaction (re-run `search`/`retrieve` if needed), and credit **only** guide-backed changes from the current turn.
- **When searched/listed in this turn but zero guides applied**: Write one first-person sentence naming which topics or guides you checked in `modern-web-guidance` and why none applied (omit if any guide applied).
+## Alternative flow: Modernize an existing codebase
+
+**Only** when asked for a broad, open-ended codebase modernization or legacy-pattern scan where no specific target feature or component is named (do **not** run `legacy-scan` when asked to add, update, fix, or audit a specific feature or component), run the 4-step modernization flow:
+
+> **Note**: `legacy-scan` scans for a curated subset (~20% of the guidance corpus).
+
+```sh
+npx -y modern-web-guidance@latest legacy-scan <path> --json
+```
+
+1. Scan: Run `legacy-scan <path> --json` to detect legacy web platform patterns across the project or directory.
+2. Verify: Check each finding against its `keepWhen` / `dropWhen` rubric; drop false positives (fallbacks, cross-file helpers, vendor code, lookalikes).
+3. Report: Summarize verified findings (and the modernization plan, if editing) for the user, noting that `legacy-scan` only checks the subset of guides (~20% of the catalog) that have deterministic legacy rules.
+4. Modernize (when the user asked to modernize rather than only audit/report): Retrieve each finding's guide (`retrieve "<guide-id>"` via Step 2), apply the replacement (keeping existing libraries as fallbacks where the guide requires one), and re-run `legacy-scan <path>` on the modified files to confirm resolution.
+ - Dropped findings and kept fallbacks still match static scans; do not edit safe code or inspect `legacy-scan.mjs` to force 0 findings.
+
## Using npx / pnpx
- **Runner & Permissions**: Prefer `pnpx` over `npx` if `pnpm` is available (`pnpx` does not use `-y`); on Windows, use `npx.cmd`. When requesting tool permissions, allowlist `npx -y modern-web-guidance@latest *` (or `pnpx modern-web-guidance@latest *`) specifically, never bare `npx *` or `pnpx *`.
@@ -69,4 +87,4 @@ When you consult `modern-web-guidance` for a task, end the response where you de
* **Default Behavior**: All guides assume **Baseline Widely available** features are safe to use without fallbacks. For features that are not Baseline widely available, you **MUST** follow the fallback recommendations in the guide, unless the user has specified a custom browser support policy.
* **Custom Policies**: If the user defines explicit browser support requirements, use the guide's compatibility data to determine if a fallback can be ignored (for `Baseline YYYY` targets, a feature satisfies the target if its "Baseline since" date is `<= YYYY`). Examples: _"Do not implement feature fallbacks"_, _"Safari 17.4+"_, _"Never implement polyfills; use a lightweight custom fallback or redesign"_, or _"Allow Newly Available features if feature-detected with graceful degradation"_.
-* **Reactive Policy Discovery**: Suggest documenting a policy in `CLAUDE.md` or `AGENTS.md` (e.g., `**Browser Support:** Allow Newly Available features, but only adopt custom fallback code that adds <= 20 lines and no external dependencies`) if the developer targets a restricted runtime (Electron/Tauri), excludes specific browsers, hesitates over polyfill size/complexity, or asks if a feature is safe without fallbacks.
+* **Reactive Policy Discovery**: Suggest documenting a policy in `AGENTS.md` or `CLAUDE.md` (e.g., `**Browser Support:** Allow Newly Available features, but only adopt custom fallback code that adds <= 20 lines and no external dependencies`) if the developer targets a restricted runtime (Electron/Tauri), excludes specific browsers, hesitates over polyfill size/complexity, or asks if a feature is safe without fallbacks.
diff --git a/skills/modern-web-guidance/guides/accessibility/accessible-error-announcement.md b/skills/modern-web-guidance/guides/accessibility/accessible-error-announcement.md
index a20796e..725b6cf 100644
--- a/skills/modern-web-guidance/guides/accessibility/accessible-error-announcement.md
+++ b/skills/modern-web-guidance/guides/accessibility/accessible-error-announcement.md
@@ -8,18 +8,19 @@ If you use standard `:invalid` styling, screen readers might announce "Invalid e
## The Solution
We want the *programmatic* state (`aria-invalid="true"`) to be applied **at the exact same moment** the *visual* state (`:user-invalid`) applies. Since `:user-invalid` relies on the browser's internal "user-interacted" flag, we can use JavaScript to check that this selector matches during standard interaction events.
-See [MDN aria-invalid](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) for more details.
+Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving the attribute unset. Firefox and Safari expose an empty `required` field as invalid from page load, so an unset attribute still causes the premature "invalid entry" announcement there.
### Implementation Strategy
1. **Visual Layer**: Use CSS `:user-invalid` to show borders/icons.
-2. **Accessibility Layer**: Use `aria-invalid` and `aria-errormessage` to communicate state to Assistive Technology (AT).
-3. **Bridge Visual & Accessibility Layer**: Create a lightweight JavaScript utility that listens for `blur` and `input` events, checks if the element matches `:user-invalid`, and updates the ARIA attributes accordingly.
+2. **Accessibility Layer**: Use `aria-invalid`, and list the error message in `aria-describedby` while the field is invalid, to communicate state to Assistive Technology (AT). Announce an error that appears when the user leaves a field through one polite live region for the page.
+3. **Bridge Visual & Accessibility Layer**: Create a lightweight JavaScript utility that listens for `blur`, `change`, `input` and `invalid` events, checks if the element matches `:user-invalid`, and updates the ARIA attributes accordingly.
+4. **Focus on Submit**: Screen readers announce a field's error when focus reaches the field, so after a failed submit, move focus to the first invalid field, or to an error summary (a heading followed by a link to each invalid field) on a long form. Native validation moves focus to the first invalid field for you; if the form uses `novalidate`, move it in your submit handler.
## Implementation Guide
### 1. HTML Structure
-Link your input to its error message using `aria-errormessage` (or `aria-describedby` for broader support).
+Link your input to its error message by setting the input's `data-error` attribute to the error message's `id`. The script in section 3 lists that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden, so the error would be read out before the user has interacted.
```html
<form>
@@ -29,7 +30,7 @@ Link your input to its error message using `aria-errormessage` (or `aria-describ
type="email"
id="email"
required
- aria-errormessage="email-error"
+ data-error="email-error"
>
<span id="email-error" class="error-msg">
Please enter a valid email address.
@@ -61,109 +62,204 @@ input:user-invalid {
### 3. JavaScript
Since there is no "UserInvalidChanged" event, hook into standard form events to check the state.
+Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
+
+* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
+* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
+* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.
+
```javascript
-const updateAriaState = (event) => {
- const input = event.target;
- if (!input.matches?.('input, textarea, select')) return;
-
- // Check if the browser currently considers this input "user-invalid"
- const isUserInvalid = input.matches(':user-invalid');
-
- if (isUserInvalid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+// List the field's error message (the id in data-error) in aria-describedby only while
+// it's shown: text that aria-describedby references is announced even when it's hidden.
+const linkError = (el, shown) => {
+ const errorId = el.dataset.error;
+ if (!errorId) return;
+ const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
+ else el.removeAttribute('aria-describedby');
};
-// Listen on the document to handle dynamically added fields.
-// 'blur' and 'focus' do not bubble, so we must use the capture phase (true).
-document.addEventListener('blur', updateAriaState, true);
-document.addEventListener('focus', updateAriaState, true);
-
-// Also update on input if we've already shown the error,
-// so the error clears immediately when fixed.
-document.addEventListener('input', (event) => {
- const input = event.target;
- if (!input.matches?.('input, textarea, select')) return;
-
- const hasAriaInvalid = input.hasAttribute('aria-invalid');
- const ariaInvalid = input.getAttribute('aria-invalid');
- if (hasAriaInvalid && ariaInvalid === 'true') {
- updateAriaState(event);
+// One polite live region for the page announces an error that appears when the user
+// leaves or changes a field. Run this once the form is in the page.
+const announcer = document.createElement('div');
+announcer.setAttribute('aria-live', 'polite');
+announcer.classList.add('visually-hidden');
+document.body.append(announcer);
+let announceTimer;
+let announcedField;
+
+// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
+const spokenText = (node) => {
+ const copy = node.cloneNode(true);
+ copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
+ copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
+ return copy.textContent.replace(/\s+/g, ' ').trim();
+};
+const announceError = (el) => {
+ const error = document.getElementById(el.dataset.error);
+ if (!error) return;
+ const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ announcedField = el;
+ // Wait until the screen reader has announced the field that receives focus next.
+ announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
+};
+
+// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
+// an aria-invalid="true" that this script didn't set (for example from a server check)
+// is left alone.
+const flagged = new WeakSet();
+// Fields whose current error has been announced, or read out by focus after a failed
+// submit. A field can become invalid while the user types, so this is tracked separately.
+const announced = new WeakSet();
+const syncAria = (el, announce = false) => {
+ if (!el.matches?.('input, select, textarea')) return;
+ const invalid = el.matches(':user-invalid');
+ if (invalid) {
+ if (announce && !announced.has(el)) {
+ announceError(el);
+ announced.add(el);
+ }
+ el.setAttribute('aria-invalid', 'true');
+ linkError(el, true);
+ flagged.add(el);
+ } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
+ el.setAttribute('aria-invalid', 'false');
+ linkError(el, false);
+ flagged.delete(el);
+ announced.delete(el);
+ // Clear a fixed field's announcement so it isn't found later when reading the page.
+ if (announcedField === el) {
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ }
}
+};
+
+// Start every field at aria-invalid="false".
+document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));
+
+// Update on blur (to show and announce an error) and input (to clear it)
+document.addEventListener('blur', (e) => syncAria(e.target, true), true);
+document.addEventListener('input', (e) => {
+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});
+
+// Checkboxes, radio buttons and other controls that commit on 'change' can become
+// :user-invalid without losing focus, so update on change too.
+document.addEventListener('change', (e) => syncAria(e.target, true), true);
+
+// A failed submit fires 'invalid' on each failing field, including required fields the
+// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
+// first invalid field announces its error, so these aren't announced.
+document.addEventListener('invalid', (e) => {
+ announced.add(e.target);
+ syncAria(e.target);
+}, true);
+
+// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
+document.addEventListener('reset', (e) => {
+ setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
+}, true);
+```
+
+Hide the live region with the `.visually-hidden` utility:
+
+```css
+/* Hides content visually but keeps it in the accessibility tree */
+.visually-hidden:where(:not(:focus-within, :active)) {
+ position: absolute !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ width: 1px !important;
+ height: 1px !important;
+ margin: -1px !important;
+ padding: 0 !important;
+ border: 0 !important;
+ white-space: nowrap !important;
+}
```
## Fallbacking & Browser Support
+### Fallbacks & browser support for :user-valid and :user-invalid
+
Baseline status for :user-valid and :user-invalid: Widely available. It's been Baseline since 2023-11-02.
Supported by: Chrome 119 (Oct 2023), Edge 119 (Nov 2023), Firefox 88 (Apr 2021), and Safari 16.5 (May 2023).
-### Feature Detection
-You can check for support in CSS and JavaScript.
-
-**JavaScript Check:**
-```javascript
-if (!CSS.supports('selector(:user-invalid)')) {
- // Fallback logic here
-}
-```
-
### CSS for Fallback
-To ensure your fallback logic is visually indistinguishable from the native behavior, you must apply your error styles to both the pseudo-class and your fallback class.
```css
-/* Apply error styles to both native selector and fallback class */
-input:user-invalid,
-input.user-invalid-fallback {
+/* Applies to every field that can be invalid (input, select, textarea). :is() keeps the
+ rule working where :user-invalid isn't supported: in a plain selector list, one
+ unsupported selector drops the whole rule. */
+:is(:user-invalid, .user-invalid-fallback) {
border-color: #d93025;
background-color: #fce8e6;
}
-/* Show error message for both cases */
-input:user-invalid ~ .error-msg,
-input.user-invalid-fallback ~ .error-msg {
+:is(:user-invalid, .user-invalid-fallback) + .error-msg {
display: block;
}
```
-### Fallback Logic
-If `:user-invalid` is missing manually track the interaction state using a `WeakMap`.
+### JavaScript Fallback
+
+Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.
```javascript
const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
- const isValid = input.checkValidity();
+ // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
+ const isValid = input.validity.valid;
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
- if (!isValid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+ input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
+ linkError(input, !isValid);
+ };
+
+ // List the error message (the id in data-error) in aria-describedby only while it's
+ // shown: text that aria-describedby references is announced even when it's hidden.
+ const linkError = (input, shown) => {
+ const errorId = input.dataset.error;
+ if (!errorId) return;
+ const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
+ else input.removeAttribute('aria-describedby');
};
const handleEvent = (event) => {
const input = event.target;
- if (event.type === 'reset' && input.matches?.('form')) {
+ if (event.type === 'reset') {
const controls = input.elements || [];
for (const control of controls) {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
- control.removeAttribute('aria-invalid');
+ if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
+ if (control.dataset?.error) linkError(control, false);
}
return;
}
- if (!input.matches?.('input, textarea, select')) return;
+ if (!input.checkValidity) return;
+
+ // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
+ // field, including required fields the user never touched, so flag them all.
+ if (event.type === 'invalid') {
+ dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
+ updateState(input);
+ return;
+ }
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
@@ -182,27 +278,25 @@ const UserInvalidFallback = (() => {
}
};
- const init = () => {
+ const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
- document.addEventListener('blur', handleEvent, true); // Capture phase required
- document.addEventListener('input', handleEvent, true);
- document.addEventListener('change', handleEvent, true);
- document.addEventListener('reset', handleEvent, true); // Capture resets
+ // Firefox and Safari expose an empty required field as invalid from page load.
+ root.querySelectorAll('input, select, textarea').forEach((el) => {
+ if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
+ });
+
+ root.addEventListener('blur', handleEvent, true); // Capture phase
+ root.addEventListener('input', handleEvent);
+ root.addEventListener('change', handleEvent);
+ root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
+ root.addEventListener('reset', handleEvent, true); // Capture resets
};
return { init };
})();
-// Initialize globally
-UserInvalidFallback.init();
+// Initialize for a specific form
+const form = document.querySelector('#demo-form');
+UserInvalidFallback.init(form);
```
-
-## Other Considerations
-
-1. **`aria-live` vs. `aria-errormessage`**:
- * `aria-errormessage` connects the input to the text, but screen readers might not announce it immediately upon appearance (only when focusing the input).
- * If you need *immediate* announcement when the error appears (e.g., on blur), consider adding `role="alert"` or `aria-live="polite"` to the error message container, but test thoroughly to avoid "double announcement" when the user focuses the field to fix it.
-
-2. **Internationalization**:
- * Ensure the text content of your error message (`#email-error`) is translated. The logic remains the same.
diff --git a/skills/modern-web-guidance/guides/built-in-ai/language-detection.md b/skills/modern-web-guidance/guides/built-in-ai/language-detection.md
index 4c156bf..8d33324 100644
--- a/skills/modern-web-guidance/guides/built-in-ai/language-detection.md
+++ b/skills/modern-web-guidance/guides/built-in-ai/language-detection.md
@@ -61,12 +61,14 @@ Avoid using the detector on very short phrases or single words, as accuracy drop
## Security and Environment
- **Iframes:** Cross-origin iframes require an explicit Permissions Policy to access the API.
+
```html
<iframe
src="https://cross-origin.example.com/"
allow="language-detector"
></iframe>
```
+
- **Web Workers:** The API is **not** currently available in Web Workers due to Permission Policy complexities.
- **Privacy:** No data is sent to Google or third parties during the detection process.
@@ -87,5 +89,6 @@ if ('LanguageDetector' in self) {
```
If the `LanguageDetector` API is unsupported or availability checks return `'unavailable'`, you must gracefully fall back:
+
1. **Remote API Fallback**: Redirect the detection request to a server endpoint or a cloud API (such as the Vertex AI Gemini API) to identify the language.
2. **Graceful Degradation**: Disable language detection elements/buttons and inform the user that client-side detection is currently unsupported in this browser, preventing any unhandled exceptions or crashes.
diff --git a/skills/modern-web-guidance/guides/built-in-ai/language-model.md b/skills/modern-web-guidance/guides/built-in-ai/language-model.md
index cca31d0..264cea3 100644
--- a/skills/modern-web-guidance/guides/built-in-ai/language-model.md
+++ b/skills/modern-web-guidance/guides/built-in-ai/language-model.md
@@ -15,24 +15,39 @@ The Prompt API is currently available in Chrome as of version 148 (Desktop) for
### Initializing the API
+**User Gesture Requirement:** When `availability()` returns `'downloadable'` or `'downloading'`, `LanguageModel.create()` starts the download and needs a user gesture, such as a button click. Call it from an event listener, not on page load, or it rejects with a `NotAllowedError`.
+
Check model availability before triggering a download:
```javascript
const availability = await LanguageModel.availability();
-// Do not call create() when unavailable — the model cannot run on this device.
-if (availability !== 'unavailable') {
- const session = await LanguageModel.create({
+function createSession() {
+ return LanguageModel.create({
monitor(m) {
// Inform the user while the model downloads so the UI doesn't appear frozen.
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
+ progressEl.value = e.loaded; // a <progress max="1"> with an accessible name
});
},
});
}
+
+// Do not call create() when unavailable — the model cannot run on this device.
+if (availability === 'available') {
+ const session = await createSession();
+} else if (availability !== 'unavailable') {
+ // Starting the download requires a user gesture.
+ downloadButton.addEventListener('click', async () => {
+ const session = await createSession();
+ downloadStatusEl.textContent = 'Model downloaded'; // a polite live region
+ });
+}
```
+Show the download progress in a `<progress>` element with an accessible name, not only in the console, and announce when the download finishes in a polite live region (WCAG 4.1.3 Status Messages). If the button that starts the download is hidden while it has focus, move focus to the download's status text (give it `tabindex="-1"`) (WCAG 2.4.3 Focus Order).
+
## 2. Core Prompting Capabilities
Session examples in this section omit `session.destroy()` for brevity. Always call `session.destroy()` when a session is no longer needed to free device memory (see Section 5).
@@ -55,13 +70,22 @@ outputEl.textContent = result;
// use for longer content so each chunk can be rendered progressively.
const stream = session.promptStreaming('Write a long story about a robot.');
let completeResult = '';
-for await (const chunk of stream) {
- completeResult += chunk;
- outputEl.append(chunk);
+outputEl.setAttribute('aria-busy', 'true'); // outputEl: <div aria-live="polite">
+try {
+ for await (const chunk of stream) {
+ completeResult += chunk;
+ outputEl.append(chunk);
+ }
+} finally {
+ outputEl.setAttribute('aria-busy', 'false');
}
console.log('Full story:', completeResult);
```
+Make the element that receives the output a polite live region that is in the page from page load, and set `aria-busy="true"` on it while a response streams in, so assistive technologies announce the complete response rather than each chunk (WCAG 4.1.3 Status Messages). Don't move focus while it streams in.
+
+**MANDATORY:** If the output language differs from the page language, set `lang` on the output element to the language declared in `expectedOutputs`, so screen readers pronounce it correctly (WCAG 3.1.2 Language of Parts).
+
### Multimodal Input
The Prompt API supports text, audio, and visual inputs (images, canvas, video frames).
@@ -103,7 +127,15 @@ const mainSession = await LanguageModel.create({
const branchA = await mainSession.clone();
const branchB = await mainSession.clone();
-// Destroy the base after cloning — the clones own their own context from here.
+
+// Run independent tasks on each clone, then destroy the clones when done.
+await branchA.prompt('Greet the crew.');
+branchA.destroy();
+
+await branchB.prompt('Chart a course.');
+branchB.destroy();
+
+// Keep mainSession if you plan to clone it again later, or destroy it once no more clones are needed.
mainSession.destroy();
```
@@ -163,7 +195,8 @@ const character = await session.prompt([
- **Resource Cleanup**: Always call `session.destroy()` when a conversation is finished to free up memory.
- **Output Safety**: Model output is untrusted. Always write results to `textContent`, not `innerHTML`, to prevent XSS injection from malicious model output.
- Use a sanitizer like the native Sanitizer API or DOMPurify if you need to allow limited HTML.
-- **Aborting Tasks**: Use `AbortController` to allow users to stop long-running generations. Pass the `signal` to `prompt()` or `promptStreaming()`, not to `LanguageModel.create()`.
+- **Aborting Tasks**: Use `AbortController` to allow users to stop long-running generations. Pass the `signal` to `prompt()` or `promptStreaming()`, not to `LanguageModel.create()`. If the stop button is hidden while it has focus, move focus to the control that started the generation (WCAG 2.4.3 Focus Order).
+- **Error Handling**: `create()`, `prompt()`, `promptStreaming()` and `JSON.parse()` can all fail, so wrap them, and the loop that reads a stream, in `try`/`catch`, and show a plain-language error in the output's live region (WCAG 3.3.1 Error Identification). Treat the `AbortError` from a user's stop as expected, not as an error.
- **Security**: Use Permission Policies to control access in iframes: `<iframe src="..." allow="language-model"></iframe>`.
- **Design**: Review the [People + AI Guidebook](https://pair.withgoogle.com/guidebook/) to ensure responsible AI implementation.
@@ -223,8 +256,9 @@ only what you need.
**Do:** Explicitly call [`destroy()`](https://developer.chrome.com/docs/ai/prompt-api#terminate_a_session) on
sessions that you no longer need, to free up memory when a feature
-is no longer in use. If you use a cloning pattern, keep the base session and
-destroy the clones you no longer need.
+is no longer in use. If you use a cloning pattern, keep the base session while
+you still need to create new clones, destroy each cloned session as soon as its
+task finishes, and destroy the base session once no further clones are needed.
**Don't:** Keep multiple large sessions active. Each session consumes memory,
which creates unnecessary resource usage and might become a problem. Sessions
@@ -297,9 +331,9 @@ output. Some ideas:
- Streaming for long content: For summaries or chat, streaming creates a per-token typewriter effect by default. This can feel natural and provide immediate feedback.
- Non-streaming for short tasks (or long async tasks): For short outputs, for example, alt-text, non-streaming can create a more polished UI. It also provides time to speculatively prepare the next AI task while the current one renders. This approach also works for longer asynchronous or background tasks. If the user is not blocked on the output to continue their journey, there is no urgent need to produce the output as it happens. Signal that the process is ongoing in the UI.
-- Visual transitions for updates: When translating or rewriting text, use animations, for example, word-morphing.
+- Visual transitions for updates: When translating or rewriting text, use animations, for example, word-morphing. For respecting reduced-motion preferences, see `motion` (via `npx -y modern-web-guidance@latest retrieve "motion"`).
-**Don't:** Update the UI without visual cues.
+**Don't:** Update the UI without visual cues, or without announcing the update to assistive technology users.
#### Align with the user's mental model of time and work
diff --git a/skills/modern-web-guidance/guides/built-in-ai/prompt-api.md b/skills/modern-web-guidance/guides/built-in-ai/prompt-api.md
index cca31d0..264cea3 100644
--- a/skills/modern-web-guidance/guides/built-in-ai/prompt-api.md
+++ b/skills/modern-web-guidance/guides/built-in-ai/prompt-api.md
@@ -15,24 +15,39 @@ The Prompt API is currently available in Chrome as of version 148 (Desktop) for
### Initializing the API
+**User Gesture Requirement:** When `availability()` returns `'downloadable'` or `'downloading'`, `LanguageModel.create()` starts the download and needs a user gesture, such as a button click. Call it from an event listener, not on page load, or it rejects with a `NotAllowedError`.
+
Check model availability before triggering a download:
```javascript
const availability = await LanguageModel.availability();
-// Do not call create() when unavailable — the model cannot run on this device.
-if (availability !== 'unavailable') {
- const session = await LanguageModel.create({
+function createSession() {
+ return LanguageModel.create({
monitor(m) {
// Inform the user while the model downloads so the UI doesn't appear frozen.
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
+ progressEl.value = e.loaded; // a <progress max="1"> with an accessible name
});
},
});
}
+
+// Do not call create() when unavailable — the model cannot run on this device.
+if (availability === 'available') {
+ const session = await createSession();
+} else if (availability !== 'unavailable') {
+ // Starting the download requires a user gesture.
+ downloadButton.addEventListener('click', async () => {
+ const session = await createSession();
+ downloadStatusEl.textContent = 'Model downloaded'; // a polite live region
+ });
+}
```
+Show the download progress in a `<progress>` element with an accessible name, not only in the console, and announce when the download finishes in a polite live region (WCAG 4.1.3 Status Messages). If the button that starts the download is hidden while it has focus, move focus to the download's status text (give it `tabindex="-1"`) (WCAG 2.4.3 Focus Order).
+
## 2. Core Prompting Capabilities
Session examples in this section omit `session.destroy()` for brevity. Always call `session.destroy()` when a session is no longer needed to free device memory (see Section 5).
@@ -55,13 +70,22 @@ outputEl.textContent = result;
// use for longer content so each chunk can be rendered progressively.
const stream = session.promptStreaming('Write a long story about a robot.');
let completeResult = '';
-for await (const chunk of stream) {
- completeResult += chunk;
- outputEl.append(chunk);
+outputEl.setAttribute('aria-busy', 'true'); // outputEl: <div aria-live="polite">
+try {
+ for await (const chunk of stream) {
+ completeResult += chunk;
+ outputEl.append(chunk);
+ }
+} finally {
+ outputEl.setAttribute('aria-busy', 'false');
}
console.log('Full story:', completeResult);
```
+Make the element that receives the output a polite live region that is in the page from page load, and set `aria-busy="true"` on it while a response streams in, so assistive technologies announce the complete response rather than each chunk (WCAG 4.1.3 Status Messages). Don't move focus while it streams in.
+
+**MANDATORY:** If the output language differs from the page language, set `lang` on the output element to the language declared in `expectedOutputs`, so screen readers pronounce it correctly (WCAG 3.1.2 Language of Parts).
+
### Multimodal Input
The Prompt API supports text, audio, and visual inputs (images, canvas, video frames).
@@ -103,7 +127,15 @@ const mainSession = await LanguageModel.create({
const branchA = await mainSession.clone();
const branchB = await mainSession.clone();
-// Destroy the base after cloning — the clones own their own context from here.
+
+// Run independent tasks on each clone, then destroy the clones when done.
+await branchA.prompt('Greet the crew.');
+branchA.destroy();
+
+await branchB.prompt('Chart a course.');
+branchB.destroy();
+
+// Keep mainSession if you plan to clone it again later, or destroy it once no more clones are needed.
mainSession.destroy();
```
@@ -163,7 +195,8 @@ const character = await session.prompt([
- **Resource Cleanup**: Always call `session.destroy()` when a conversation is finished to free up memory.
- **Output Safety**: Model output is untrusted. Always write results to `textContent`, not `innerHTML`, to prevent XSS injection from malicious model output.
- Use a sanitizer like the native Sanitizer API or DOMPurify if you need to allow limited HTML.
-- **Aborting Tasks**: Use `AbortController` to allow users to stop long-running generations. Pass the `signal` to `prompt()` or `promptStreaming()`, not to `LanguageModel.create()`.
+- **Aborting Tasks**: Use `AbortController` to allow users to stop long-running generations. Pass the `signal` to `prompt()` or `promptStreaming()`, not to `LanguageModel.create()`. If the stop button is hidden while it has focus, move focus to the control that started the generation (WCAG 2.4.3 Focus Order).
+- **Error Handling**: `create()`, `prompt()`, `promptStreaming()` and `JSON.parse()` can all fail, so wrap them, and the loop that reads a stream, in `try`/`catch`, and show a plain-language error in the output's live region (WCAG 3.3.1 Error Identification). Treat the `AbortError` from a user's stop as expected, not as an error.
- **Security**: Use Permission Policies to control access in iframes: `<iframe src="..." allow="language-model"></iframe>`.
- **Design**: Review the [People + AI Guidebook](https://pair.withgoogle.com/guidebook/) to ensure responsible AI implementation.
@@ -223,8 +256,9 @@ only what you need.
**Do:** Explicitly call [`destroy()`](https://developer.chrome.com/docs/ai/prompt-api#terminate_a_session) on
sessions that you no longer need, to free up memory when a feature
-is no longer in use. If you use a cloning pattern, keep the base session and
-destroy the clones you no longer need.
+is no longer in use. If you use a cloning pattern, keep the base session while
+you still need to create new clones, destroy each cloned session as soon as its
+task finishes, and destroy the base session once no further clones are needed.
**Don't:** Keep multiple large sessions active. Each session consumes memory,
which creates unnecessary resource usage and might become a problem. Sessions
@@ -297,9 +331,9 @@ output. Some ideas:
- Streaming for long content: For summaries or chat, streaming creates a per-token typewriter effect by default. This can feel natural and provide immediate feedback.
- Non-streaming for short tasks (or long async tasks): For short outputs, for example, alt-text, non-streaming can create a more polished UI. It also provides time to speculatively prepare the next AI task while the current one renders. This approach also works for longer asynchronous or background tasks. If the user is not blocked on the output to continue their journey, there is no urgent need to produce the output as it happens. Signal that the process is ongoing in the UI.
-- Visual transitions for updates: When translating or rewriting text, use animations, for example, word-morphing.
+- Visual transitions for updates: When translating or rewriting text, use animations, for example, word-morphing. For respecting reduced-motion preferences, see `motion` (via `npx -y modern-web-guidance@latest retrieve "motion"`).
-**Don't:** Update the UI without visual cues.
+**Don't:** Update the UI without visual cues, or without announcing the update to assistive technology users.
#### Align with the user's mental model of time and work
diff --git a/skills/modern-web-guidance/guides/built-in-ai/summarizer.md b/skills/modern-web-guidance/guides/built-in-ai/summarizer.md
index f8c5926..11da0ba 100644
--- a/skills/modern-web-guidance/guides/built-in-ai/summarizer.md
+++ b/skills/modern-web-guidance/guides/built-in-ai/summarizer.md
@@ -8,7 +8,6 @@ The **Summarizer API** allows web developers to offer local, AI-powered text dis
The Summarizer API is available starting in **Chrome and Edge 138**. It requires a one-time model download of Gemini Nano or Phi (respectively).
-
### Hardware & Software Requirements
- **OS**: Windows 10/11, macOS 13+, Linux, or ChromeOS (Chromebook Plus).
@@ -93,6 +92,8 @@ const summarizer = await Summarizer.create({
});
```
+**MANDATORY:** if the output language is different from the overall page language, you **MUST** apply the `lang` attribute to the container element for the summary, and set its value to match the BCP 47 language code set using the `outputLanguage` property.
+
## Summarization Methods
### 1. Batch Summarization
@@ -125,9 +126,11 @@ for await (const chunk of stream) {
device.
- **Cross-Origin**: Access can be granted to iframes using the Permission
Policy.
+
```html
<iframe src="https://example.com/" allow="summarizer"></iframe>
```
+
- **Web Workers**: Currently not supported.
## Fallback Strategy
@@ -149,6 +152,7 @@ if ('Summarizer' in self) {
If the `Summarizer` API is unsupported or availability checks return `'unavailable'`, you must gracefully fall back.
Recommended options:
+
1. **Remote API Fallback**: Direct the distillation request to a server endpoint or remote API (such as the Vertex AI Gemini API) so that users still get summaries.
2. **Graceful Degradation**: Visually disable the summarization controls in the UI, or hide the button while displaying a friendly message (e.g., `"Local summarization is currently unsupported in this browser"`). Do not allow interaction to trigger generic unhandled runtime exceptions.
3. **Polyfill Fallback**: You can use community-maintained polyfills like `built-in-ai-task-apis-polyfills` or `prompt-api-polyfill` to emulate the API surface using remote services with models in the cloud or on-device inference with local models.
diff --git a/skills/modern-web-guidance/guides/css/animate-to-intrinsic-sizes.md b/skills/modern-web-guidance/guides/css/animate-to-intrinsic-sizes.md
index 5a94c61..a5ce2e1 100644
--- a/skills/modern-web-guidance/guides/css/animate-to-intrinsic-sizes.md
+++ b/skills/modern-web-guidance/guides/css/animate-to-intrinsic-sizes.md
@@ -45,7 +45,7 @@ You can apply this pattern to any container (like a "Show More" section or a nav
transition: inline-size 0.3s ease;
}
-.badge:hover {
+.badge:is(:hover, :focus-visible) {
/* calc-size(basis, calculation) */
/* 'size' refers to the evaluated basis (max-content in this case) */
inline-size: calc-size(max-content, size + 20px);
@@ -84,11 +84,17 @@ You can also animate in the opposite direction—starting from a natural size an
```javascript
// MANDATORY Accessibility Synchronization: Ensure elements collapsed to zero dimensions are removed from the assistive technology tree, and sync aria-expanded states on triggers.
const alertElement = document.querySelector('.collapsible-alert');
-alertElement.addEventListener('transitionend', (e) => {
- if (e.propertyName === 'block-size' && alertElement.classList.contains('is-dismissed')) {
- alertElement.hidden = true;
- }
-});
+function dismissAlert() {
+ alertElement.classList.add('is-dismissed');
+ // Waits for the transitions the class starts, ignoring any other animations
+ // on the element; under reduced motion there are none
+ const transitions = alertElement.getAnimations().filter((animation) => animation instanceof CSSTransition);
+ Promise.allSettled(transitions.map((transition) => transition.finished)).then(() => {
+ if (alertElement.classList.contains('is-dismissed')) {
+ alertElement.hidden = true;
+ }
+ });
+}
// Example trigger syncer
const triggerBtn = document.querySelector('.accordion-trigger');
diff --git a/skills/modern-web-guidance/guides/css/atrule-support-conditionals.md b/skills/modern-web-guidance/guides/css/atrule-support-conditionals.md
index b368095..81250ff 100644
--- a/skills/modern-web-guidance/guides/css/atrule-support-conditionals.md
+++ b/skills/modern-web-guidance/guides/css/atrule-support-conditionals.md
@@ -51,7 +51,7 @@ E.g. this will not work:
```
For many types of container queries, you can use `container-type` with a suitable value.
-E.g. `@supports (container-type: scroll-state)` for scroll-state queries or `@supports (container-type: size)`container-type: anchored` for `anchored()` queries.
+E.g. `@supports (container-type: scroll-state)` for scroll-state queries, `@supports (container-type: size)` for size queries, or `@supports (container-type: anchored)` for `anchored()` queries.
However, there is no `container-type` for style queries.
IMPORTANT: Do NOT try `@supports (container-type: style)` to detect support for style queries, as this will not work.
@@ -89,8 +89,6 @@ In some cases, if the conditional CSS to apply can be reduced to a single proper
For a more general-purpose solution, you can register a non-inheriting property and set it to ` ` (a space) on the root element:
-{# Testcase: https://codepen.io/leaverou/pen/KwWzpVr #}
-
```css
@property --supports-atproperty {
syntax: "*";
diff --git a/skills/modern-web-guidance/guides/css/calculate-with-intrinsic-sizes.md b/skills/modern-web-guidance/guides/css/calculate-with-intrinsic-sizes.md
index 128620a..1eb062c 100644
--- a/skills/modern-web-guidance/guides/css/calculate-with-intrinsic-sizes.md
+++ b/skills/modern-web-guidance/guides/css/calculate-with-intrinsic-sizes.md
@@ -64,12 +64,14 @@ By default, browsers cannot interpolate between a length (e.g., `0px`) and an in
.item {
height: 0;
- transition: height 0.3s ease;
+ visibility: hidden;
+ transition: height 0.3s ease, visibility 0.3s;
}
.item.open {
/* Simple interpolation from 0 to auto now works without calc-size() */
height: auto;
+ visibility: visible;
}
```
@@ -81,7 +83,10 @@ By default, browsers cannot interpolate between a length (e.g., `0px`) and an in
overflow: hidden;
/* MANDATORY: Fallback value for closed state */
block-size: 0;
- transition: block-size 0.3s ease-out;
+ /* Removes the closed content from the accessibility tree and the tab order;
+ transitioning visibility keeps it visible until the panel finishes closing */
+ visibility: hidden;
+ transition: block-size 0.3s ease-out, visibility 0.3s;
}
.accordion-content.open {
@@ -93,9 +98,12 @@ By default, browsers cannot interpolate between a length (e.g., `0px`) and an in
intrinsic size while doing a calculation (in this case, adding a space of 2rem).
*/
block-size: calc-size(auto, size + 2rem);
+ visibility: visible;
}
```
+**MANDATORY**: Collapsing to zero size (`block-size: 0` or `height: 0`) hides content only visually: screen readers still read it, and its links and controls stay in the tab order. Set `visibility: hidden` on the closed state and `visibility: visible` on the open state, and include `visibility` in the transition so the content stays visible until it has finished closing.
+
**MANDATORY**: Interpolation between two intrinsic sizing keywords is not possible directly. One end of the transition must be a length or a percentage.
#### Respecting User Motion Preferences
@@ -104,11 +112,13 @@ Animations that change the size of large layout areas can be particularly disrup
```css
.accordion-content {
opacity: 0;
- transition: block-size 0.3s ease, opacity 0.3s ease;
+ visibility: hidden;
+ transition: block-size 0.3s ease, opacity 0.3s ease, visibility 0.3s;
}
.accordion-content.open {
opacity: 1;
+ visibility: visible;
}
@media (prefers-reduced-motion: reduce) {
diff --git a/skills/modern-web-guidance/guides/css/child-state-based-styling.md b/skills/modern-web-guidance/guides/css/child-state-based-styling.md
index 2c9a314..71b1616 100644
--- a/skills/modern-web-guidance/guides/css/child-state-based-styling.md
+++ b/skills/modern-web-guidance/guides/css/child-state-based-styling.md
@@ -6,7 +6,7 @@ By combining `:has()` with state pseudo-classes (like `:checked`, `:focus`, `:va
This is particularly useful for components that need to respond to internal interactions, such as a localized theme toggle reacting to a checkbox (`:checked`), a form group highlighting an error (`:invalid`), or a card elevating when a child link is focused (`:focus-within`).
-### Implementing state-based container styling
+## Implementing state-based container styling
**MANDATORY**: You must use the `:has()` selector on the container element to detect the specific state (e.g., `:checked`, `:focus`, `:invalid`) of its interactive child element.
@@ -64,7 +64,7 @@ To build a component that changes its styling based on a child's state:
**Performance tip**: When using `:has()`, scope the selector to the most specific container possible (like `.theme-card`). Avoid anchoring it to very high-level elements like `body:has(...)` if the styling changes are localized, as broad `:has()` queries can trigger more layout recalculations.
-### Fallback strategies
+## Fallback strategies
Baseline status for :has(): Widely available. It's been Baseline since 2023-12-19.
Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 121 (Dec 2023), and Safari 15.4 (Mar 2022).
diff --git a/skills/modern-web-guidance/guides/css/css-layout.md b/skills/modern-web-guidance/guides/css/css-layout.md
index 2a59b95..4555879 100644
--- a/skills/modern-web-guidance/guides/css/css-layout.md
+++ b/skills/modern-web-guidance/guides/css/css-layout.md
@@ -250,6 +250,8 @@ Manage layout shifts, scrollbars, and clipping predictably.
- Use `scrollbar-gutter: stable` to reserve space for scrollbars and prevent layout shifts when content grows.
- Use `overscroll-behavior: contain` (or `none`) on nested scroll regions (such as sidebars, modals, and lists) to stop scroll chains from bubbling into the page, or `overscroll-behavior: chain` on intermediate scroll wrappers (such as swipe-to-reveal tracks) when excess scroll should propagate to an ancestor scroller without triggering a local rubber-band bounce.
- Use the `-webkit-line-clamp` + `display: -webkit-box` + `-webkit-box-orient: vertical` triad for multi-line truncation — despite the prefix, this pattern is fully specified and not deprecated. Declare the unprefixed `line-clamp` shorthand alongside it; browsers that don't yet support it ignore the property harmlessly.
+- For text that must stay on one line (labels, table cells, file names) see `single-line-overflow` (via `npx -y modern-web-guidance@latest retrieve "single-line-overflow"`) for techniques for truncating and revealing the full text on demand without UX friction.
+
**Do not:**
- Don't use `overflow: scroll` when `auto` will do — `scroll` forces scrollbars even when there's nothing to scroll.
diff --git a/skills/modern-web-guidance/guides/css/fluid-scaling.md b/skills/modern-web-guidance/guides/css/fluid-scaling.md
index 8b91d5c..df1a371 100644
--- a/skills/modern-web-guidance/guides/css/fluid-scaling.md
+++ b/skills/modern-web-guidance/guides/css/fluid-scaling.md
@@ -49,6 +49,8 @@ Use container query units (`cqi`, `cqb`, etc.) to set sizes relative to the cont
To prevent sizes from becoming too small or too large, use the CSS `clamp()` function. This impacts the user's ability to zoom or adjust their base font size. To ensure text meets accessibility guidelines, the maximum size must not be more than 2.5 times the minimum size.
+**DON'T** make the container smaller when zooming in with the browser. This is to ensure that text can be resized to 200% its default size when zooming in using the browser to adhere to WCAG 1.4.4 Resize Text (Level AA).
+
```css
.component-title {
/* Clamp font size between 1rem and 2.5rem, scaling with 5% of container width */
diff --git a/skills/modern-web-guidance/guides/css/responsive-design.md b/skills/modern-web-guidance/guides/css/responsive-design.md
index 5ea79aa..201139c 100644
--- a/skills/modern-web-guidance/guides/css/responsive-design.md
+++ b/skills/modern-web-guidance/guides/css/responsive-design.md
@@ -10,7 +10,7 @@ For the layout mechanics behind responsive UI (flexbox, grid, container query un
## Responsive typography
-- **DO** combine viewport-relative and font-relative units in `clamp()` for font sizes that scale with the viewport size while ensuring they stay within a desired range. For example, `clamp(2rem, 1rem + 5vw, 4rem)`. Adjust the proportion of viewport-relative and font-relative units to control how quickly the font-size changes.
+- **DO** combine viewport-relative and font-relative units in `clamp()` for font sizes that scale with the viewport size while ensuring they stay within a desired range. For example, `clamp(2rem, 1rem + 5vw, 4rem)`. Adjust the proportion of viewport-relative and font-relative units to control how quickly the font-size changes. Use font-relative minimum and maximum values, and keep the maximum no more than 2.5 times the minimum. Viewport units don't grow when users zoom, so the text only grows once its minimum overtakes the viewport-based value; with a maximum no more than 2.5 times the minimum, browser zoom, which goes up to 500%, can still resize the text to 200% (WCAG 1.4.4 Resize Text requires text to resize up to 200% without loss of content or functionality).
- **DON'T** use `vw` alone for font-size without `clamp()`, as it can scale text too small or too large on extreme screens.
To scale type and spacing with the container instead of the viewport, see `fluid-scaling` (via `npx -y modern-web-guidance@latest retrieve "fluid-scaling"`).
diff --git a/skills/modern-web-guidance/guides/css/style-parent-with-has.md b/skills/modern-web-guidance/guides/css/style-parent-with-has.md
index 99e6f5a..52eb109 100644
--- a/skills/modern-web-guidance/guides/css/style-parent-with-has.md
+++ b/skills/modern-web-guidance/guides/css/style-parent-with-has.md
@@ -1,4 +1,4 @@
-# Style Parent with :has()
+# Style a Form Group When a Field Is Invalid with :has()
## The Problem
Often, an error state requires styling elements *outside* the input itself—for example, changing the color of a parent `fieldset` border, highlighting the `<label>`, or showing a global error icon in the card header. Historically, this required JavaScript to toggle classes on parent elements.
@@ -50,10 +50,12 @@ By combining `:has()` with `:user-invalid`, we can declaratively style any ances
/* Change the icon too */
.card-section:has(:user-invalid) .status-icon::after {
- content: "⚠️";
+ content: "⚠️" / "Error";
}
```
+Parent styling only adds emphasis: it doesn't say which field is wrong or why, so each field still needs its own visible error text. See `required-field-feedback` (via `npx -y modern-web-guidance@latest retrieve "required-field-feedback"`).
+
## Fallbacking & Browser Support
Baseline status for :user-valid and :user-invalid: Widely available. It's been Baseline since 2023-11-02.
@@ -83,17 +85,26 @@ const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
- const isValid = input.checkValidity();
+ // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
+ const isValid = input.validity.valid;
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
- if (!isValid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+ input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
+ linkError(input, !isValid);
+ };
+
+ // List the error message (the id in data-error) in aria-describedby only while it's
+ // shown: text that aria-describedby references is announced even when it's hidden.
+ const linkError = (input, shown) => {
+ const errorId = input.dataset.error;
+ if (!errorId) return;
+ const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
+ else input.removeAttribute('aria-describedby');
};
const handleEvent = (event) => {
@@ -105,13 +116,22 @@ const UserInvalidFallback = (() => {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
- control.removeAttribute('aria-invalid');
+ if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
+ if (control.dataset?.error) linkError(control, false);
}
return;
}
if (!input.checkValidity) return;
+ // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
+ // field, including required fields the user never touched, so flag them all.
+ if (event.type === 'invalid') {
+ dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
+ updateState(input);
+ return;
+ }
+
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasInteracted = true;
@@ -132,9 +152,15 @@ const UserInvalidFallback = (() => {
const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
+ // Firefox and Safari expose an empty required field as invalid from page load.
+ root.querySelectorAll('input, select, textarea').forEach((el) => {
+ if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
+ });
+
root.addEventListener('blur', handleEvent, true); // Capture phase
root.addEventListener('input', handleEvent);
root.addEventListener('change', handleEvent);
+ root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
root.addEventListener('reset', handleEvent, true); // Capture resets
};
@@ -152,49 +178,168 @@ const form = document.querySelector('#demo-form');
UserInvalidFallback.init(form);
// 2. Add specialized "parent styling" logic (Separate from fallback)
-// Listen for changes to form validity after interaction
-form.addEventListener('blur', (e) => {
- if (!e.target.matches('input, select, textarea')) return;
-
- // Find the container we want to style (sync with CSS)
- const container = e.target.closest('.card-section');
- if (!container) return;
-
- // Check if ANY fallbacked input in this container is invalid
- const hasError = container.querySelector('.user-invalid-fallback');
- container.classList.toggle('has-error-fallback', !!hasError);
-}, true); // Capture phase to ensure we run after the fallback's blur listener
-
-// Also handle input events for immediate cleanup
-form.addEventListener('input', (e) => {
- const container = e.target.closest('.card-section');
- if (container) {
- const hasError = container.querySelector('.user-invalid-fallback');
+const supportsHas = CSS.supports('selector(:has(a))');
+if (!supportsHas) {
+ // Listen for changes to form validity after interaction
+ form.addEventListener('blur', (e) => {
+ if (!e.target.matches('input, select, textarea')) return;
+
+ // Find the container we want to style (sync with CSS)
+ const container = e.target.closest('.card-section');
+ if (!container) return;
+
+ // Check if ANY input in this container is invalid. Match :user-invalid as well as the
+ // fallback class: a browser can support :user-invalid but not :has().
+ const hasError = container.querySelector(':is(:user-invalid, .user-invalid-fallback)');
container.classList.toggle('has-error-fallback', !!hasError);
- }
-});
+ }, true); // Capture phase to ensure we run after the fallback's blur listener
+
+ // Also handle input events for immediate cleanup
+ form.addEventListener('input', (e) => {
+ const container = e.target.closest('.card-section');
+ if (container) {
+ const hasError = container.querySelector(':is(:user-invalid, .user-invalid-fallback)');
+ container.classList.toggle('has-error-fallback', !!hasError);
+ }
+ });
-// Handle form resets
-form.addEventListener('reset', () => {
- form.querySelectorAll('.has-error-fallback').forEach(el => {
- el.classList.remove('has-error-fallback');
+ // A submit attempt flags every failing field through the invalid event, the only event
+ // it fires on fields the user never touched. invalid doesn't bubble, so use the capture phase.
+ form.addEventListener('invalid', (e) => {
+ const container = e.target.closest('.card-section');
+ if (container) {
+ const hasError = container.querySelector(':is(:user-invalid, .user-invalid-fallback)');
+ container.classList.toggle('has-error-fallback', !!hasError);
+ }
+ }, true);
+
+ // Handle form resets
+ form.addEventListener('reset', () => {
+ form.querySelectorAll('.has-error-fallback').forEach(el => {
+ el.classList.remove('has-error-fallback');
+ });
});
-});
+}
```
## Other Considerations
1. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
+* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
+* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
+* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.
+
```javascript
-// Sync aria-invalid with the CSS :user-invalid state
-const syncAria = (el) => {
- el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
+// List the field's error message (the id in data-error) in aria-describedby only while
+// it's shown: text that aria-describedby references is announced even when it's hidden.
+const linkError = (el, shown) => {
+ const errorId = el.dataset.error;
+ if (!errorId) return;
+ const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
+ else el.removeAttribute('aria-describedby');
+};
+
+// One polite live region for the page announces an error that appears when the user
+// leaves or changes a field. Run this once the form is in the page.
+const announcer = document.createElement('div');
+announcer.setAttribute('aria-live', 'polite');
+announcer.classList.add('visually-hidden');
+document.body.append(announcer);
+let announceTimer;
+let announcedField;
+
+// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
+const spokenText = (node) => {
+ const copy = node.cloneNode(true);
+ copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
+ copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
+ return copy.textContent.replace(/\s+/g, ' ').trim();
+};
+const announceError = (el) => {
+ const error = document.getElementById(el.dataset.error);
+ if (!error) return;
+ const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ announcedField = el;
+ // Wait until the screen reader has announced the field that receives focus next.
+ announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
+};
+
+// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
+// an aria-invalid="true" that this script didn't set (for example from a server check)
+// is left alone.
+const flagged = new WeakSet();
+// Fields whose current error has been announced, or read out by focus after a failed
+// submit. A field can become invalid while the user types, so this is tracked separately.
+const announced = new WeakSet();
+const syncAria = (el, announce = false) => {
+ if (!el.matches?.('input, select, textarea')) return;
+ const invalid = el.matches(':user-invalid');
+ if (invalid) {
+ if (announce && !announced.has(el)) {
+ announceError(el);
+ announced.add(el);
+ }
+ el.setAttribute('aria-invalid', 'true');
+ linkError(el, true);
+ flagged.add(el);
+ } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
+ el.setAttribute('aria-invalid', 'false');
+ linkError(el, false);
+ flagged.delete(el);
+ announced.delete(el);
+ // Clear a fixed field's announcement so it isn't found later when reading the page.
+ if (announcedField === el) {
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ }
+ }
};
-// Update on blur (to show error) and input (to clear it)
-document.addEventListener('blur', (e) => syncAria(e.target), true);
+// Start every field at aria-invalid="false".
+document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));
+
+// Update on blur (to show and announce an error) and input (to clear it)
+document.addEventListener('blur', (e) => syncAria(e.target, true), true);
document.addEventListener('input', (e) => {
if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});
+
+// Checkboxes, radio buttons and other controls that commit on 'change' can become
+// :user-invalid without losing focus, so update on change too.
+document.addEventListener('change', (e) => syncAria(e.target, true), true);
+
+// A failed submit fires 'invalid' on each failing field, including required fields the
+// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
+// first invalid field announces its error, so these aren't announced.
+document.addEventListener('invalid', (e) => {
+ announced.add(e.target);
+ syncAria(e.target);
+}, true);
+
+// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
+document.addEventListener('reset', (e) => {
+ setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
+}, true);
+```
+
+Hide the live region with the `.visually-hidden` utility:
+
+```css
+/* Hides content visually but keeps it in the accessibility tree */
+.visually-hidden:where(:not(:focus-within, :active)) {
+ position: absolute !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ width: 1px !important;
+ height: 1px !important;
+ margin: -1px !important;
+ padding: 0 !important;
+ border: 0 !important;
+ white-space: nowrap !important;
+}
```
diff --git a/skills/modern-web-guidance/guides/forms/animated-select-picker.md b/skills/modern-web-guidance/guides/forms/animated-select-picker.md
index 6976832..05b587a 100644
--- a/skills/modern-web-guidance/guides/forms/animated-select-picker.md
+++ b/skills/modern-web-guidance/guides/forms/animated-select-picker.md
@@ -10,7 +10,7 @@ To implement an animated select picker:
1. **Opt-in to customization:** Apply `appearance: base-select` to both the `<select>` element and the `::picker(select)` pseudo-element.
2. **Enable auto-sizing transitions (Optional):** Define `interpolate-size: allow-keywords` (usually on `:root`) to allow the browser to transition between discrete metric values like `height: auto` and `height: 0`.
-3. **Animate the top-layer container:** Apply standard entry/exit styles to `::picker(select)`. To make sure the opacity transition works when moving between `display: none` and `display: block`, you must use `transition-behavior: allow-discrete` (often written inline as `transition: display 0.3s allow-discrete`).
+3. **Animate the top-layer container:** Apply standard entry/exit styles to `::picker(select)`. Include `display` and `overlay` in the `transition` property and set `transition-behavior: allow-discrete` so the picker stays rendered in the top layer when transitioning between `display: none` and `display: block`.
4. **Hook into the opening state with `@starting-style`:** Use `@starting-style` to define the baseline styles the browser should compute *before* the transition begins. For example, if you want it to fade in, set the opacity to `0` inside the `@starting-style` block.
5. **Rotate the icon:** Use pseudo-element focus or active selectors like `:open::picker-icon` to apply transitions (such as rotation or translation) to the arrow indicator.
@@ -91,20 +91,23 @@ The following example demonstrates a custom select styled with standard page ani
* Uses top-layer animations with `allow-discrete` visibility hooks
*/
.animated-select::picker(select) {
+ /* Set a text color with the background so options stay readable on pages with a dark color scheme */
background: white;
+ color: black;
border-radius: 12px;
box-shadow: 0 10px 25px -3px rgba(0,0,0,0.1);
padding: 0.5rem;
margin-top: 0.25rem;
width: anchor-size(width);
- overflow: hidden;
- /* The crucial transition setting for popover animations */
transition:
- display 0.4s allow-discrete,
- overlay 0.4s allow-discrete,
- opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1),
- height 0.4s cubic-bezier(0.16, 1, 0.3, 1);
+ display,
+ overlay,
+ opacity cubic-bezier(0.16, 1, 0.3, 1),
+ height cubic-bezier(0.16, 1, 0.3, 1);
+ transition-duration: 0.4s;
+ /* Separate after transition so the shorthand doesn't reset it or fail in older browsers */
+ transition-behavior: allow-discrete;
opacity: 0;
height: 0;
}
@@ -135,6 +138,7 @@ The following example demonstrates a custom select styled with standard page ani
.animated-select option:checked {
font-weight: 700;
background-color: #f1f5f9;
+ color: black;
}
/* Ensure copy-paste safety for users with motion sensitivities */
@@ -149,7 +153,9 @@ The following example demonstrates a custom select styled with standard page ani
## Strategic Implementation & Best Practices
- **DO** use `@starting-style` when you need animations to trigger exactly when an element transitions from `display: none` to visible.
+- **DO NOT** use `allow-discrete` in the `transition` shorthand — it will make older browsers ignore the entire `transition` declaration. Except in use cases where that is desirable, use a separate `transition-behavior: allow-discrete` declaration.
- **DO NOT** use ad-hoc scroll locking. Top-layer elements managed by ‘base-select’ should allow natural backdrop dismiss behaviors.
+- **DO NOT** set `overflow: hidden` on `::picker(select)`. The picker must stay scrollable so that options that don't fit in the available space, for example at high zoom or in a short viewport, can still be reached.
- **DO** verify reduced motion preferences. Always wrap animation constraints in a `prefers-reduced-motion` media query to ensure accessible environments for those affected by motion sickness.
- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
diff --git a/skills/modern-web-guidance/guides/forms/autofill-address-form.md b/skills/modern-web-guidance/guides/forms/autofill-address-form.md
index 9050337..9513c71 100644
--- a/skills/modern-web-guidance/guides/forms/autofill-address-form.md
+++ b/skills/modern-web-guidance/guides/forms/autofill-address-form.md
@@ -21,7 +21,7 @@ To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a
### Make the most of HTML attributes
-Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
+Make it easy for users to enter data, by using the appropriate `<input>` element with a `type` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
Always use `type="email"` for email addresses and `type="tel"` for phone numbers.
@@ -41,7 +41,11 @@ Give each form submit button a value that says what it does. For each step towar
### Use a single name input where possible
-Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.
+Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler. Use `autocomplete="name"` for a single input for name.
+
+```html
+<input type="text" id="fullname" name="fullname" autocomplete="name">
+```
Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.
diff --git a/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md b/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md
index f3fe6f2..1f1affb 100644
--- a/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md
+++ b/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md
@@ -1,45 +1,63 @@
-# Highlight browser-autofilled fields the user hasn't edited with CSS :autofill
+# Customize the styling of autofilled form fields
-Use the CSS `:autofill` to highlight fields that have (or have not been) autofilled, to help guide the user to successful form completion.
+Use the CSS `:autofill` pseudo-class to replace the browser's default highlight for autofilled `<input>`, `<select>`, and `<textarea>` elements. It matches fields filled by the browser or by the user picking an autofill suggestion, and stops matching once the user edits the field, even if the value is identical.
-## How to implement
-
-To highlight a form field that has been autofilled by the browser (and not edited by the user) add a selector to your CSS using the `:autofill` class. This can be used for an `<input>`, `<select>`, or `<textarea>` element.
+It never matches checkbox, radio, file, or button inputs, form-associated custom elements, or `contenteditable`: browsers do not autofill those. A native control inside a custom element's shadow DOM matches; style it from inside, or via `::part(name):autofill`.
-When styling autofilled states, you must adhere to accessibility best practices:
-- **Multiple State Indicators**: Do not rely on border color alone to indicate the autofilled state. Use multiple indicators such as border thickness and custom background shading to ensure the state is perceivable.
-- **Preserve Focus Indicators**: Never remove focus outlines (`outline: none`) without providing a clear, high-contrast replacement for keyboard users.
+## How to implement
-The following example uses `:autofill` to set a custom border and background, along with explicit focus styles:
+- Add at least one non-color indicator (e.g. a thicker inset ring). The browser's default highlight is color only.
+- Do not remove the focus outline (`outline: none`). If you use `outline` for the autofill styling, give `:autofill:focus-visible` an outline that differs in more than color (e.g. thickness, style, or offset) so focus remains perceivable.
+- Do not change layout-affecting properties (`border-width`, `padding`); the state toggles with user activity so that would shift content.
```css
-input:autofill,
-input:-webkit-autofill {
- /* Multiple indicators: use both a distinct border and background color via box-shadow to avoid color-only state */
- border: 2px solid #2e7d32;
- box-shadow: 0 0 0 100vmax #e8f5e9 inset;
-}
-
-/* MANDATORY: Always provide an explicit focus indicator when styling autofilled states */
-input:autofill:focus-visible,
-input:-webkit-autofill:focus-visible {
- outline: 3px solid #000;
- outline-offset: 2px;
+input:autofill {
+ /* Non-color indicator without layout shift: a thicker inset ring */
+ box-shadow: inset 0 0 0 2px var(--autofill-ring-color);
+ border-color: var(--autofill-ring-color);
}
```
-As shown in this example, the `box-shadow` property is used to customize the background, since `background-color` cannot be overridden directly on autofilled fields.
+### Overriding the background and text color
-## Use the correct CSS pseudo-class name
+Prefer to keep the browser's background and text color. Users have learned that the default highlight means "this was autofilled", and replacing it breaks that association.
+All browsers also set `background-color`, `background-image`, and `color` on autofilled fields with `!important` in their user agent stylesheets, so overriding them relies on workarounds.
-**Do not** use `:auto-fill`: this is incorrect.
+If your design requires it:
-MANDATORY: Use `:autofill` as this is the correct pseudo-class name.
+```css
+input:autofill {
+ /* Fill: an inset box-shadow paints over the UA's `!important` background */
+ box-shadow:
+ inset 0 0 0 2px var(--autofill-ring-color),
+ inset 0 0 0 100vmax var(--autofill-background-color);
+ /* Text color: -webkit-text-fill-color is not set by the UA */
+ -webkit-text-fill-color: var(--autofill-text-color);
+ /* The caret still follows the UA's `color`, so set it explicitly */
+ caret-color: var(--autofill-text-color);
+}
+```
-### Fallback strategies
+Caveats:
+- The UA text color is `FieldText`: black in a light color scheme, white in a dark one. Keep the fill legible against it (e.g. via `light-dark()`), so the field stays readable even if the text color override does not apply.
+- The fill is painted over the browser's color, not your page background, so use an opaque `--autofill-background-color`.
+- The rule replaces any other `box-shadow` on the field (e.g. a focus ring done with `box-shadow`); repeat those shadows in the same declaration.
+- `-webkit-text-fill-color` changes painted text only. `color`, and therefore `currentColor`, still resolve to the UA's `FieldText`.
+
+## Fallback strategies
Browser support for :autofill: Limited availability.
Supported by: Chrome 110 (Feb 2023), Edge 110 (Feb 2023), and Safari 15 (Sep 2021).
Unsupported in: Firefox.
-The `:autofill` pseudo-class is a progressive enhancement. In browsers that do not support it, the form will still function normally, but the inputs will simply not receive the custom autofill highlighting. Users will still be able to successfully complete the form. No additional JavaScript fallback should be used.
+Firefox only matches `:autofill` on autofilled username and password fields (bug 1923525). No workaround; other fields keep the default tint.
+
+Chrome before 110 and Safari before 15 only support `:-webkit-autofill`. If they are in your Baseline target, wrap both names in `:is()` so an unrecognized pseudo-class does not invalidate the whole rule:
+
+```css
+input:is(:autofill, :-webkit-autofill) {
+ /* same declarations as above */
+}
+```
+
+This is progressive enhancement: unsupported browsers keep their default highlight. Do not add a JavaScript fallback.
diff --git a/skills/modern-web-guidance/guides/forms/autofill-payment-form.md b/skills/modern-web-guidance/guides/forms/autofill-payment-form.md
index 7ba4e34..7bbb766 100644
--- a/skills/modern-web-guidance/guides/forms/autofill-payment-form.md
+++ b/skills/modern-web-guidance/guides/forms/autofill-payment-form.md
@@ -23,7 +23,7 @@ To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a
### Make the most of HTML attributes
-Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
+Make it easy for users to enter data, by using the appropriate `<input>` element with a `type` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
Always use `type="email"` for email addresses and `type="tel"` for phone numbers.
@@ -43,7 +43,11 @@ Give each form submit button a value that says what it does. For each step towar
### Use a single name input where possible
-Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.
+Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler. Use `autocomplete="name"` for a single input for name.
+
+```html
+<input type="text" id="fullname" name="fullname" autocomplete="name">
+```
Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.
diff --git a/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md b/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md
index 2acf442..9d0a2bc 100644
--- a/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md
+++ b/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md
@@ -23,7 +23,7 @@ To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a
### Make the most of HTML attributes
-Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
+Make it easy for users to enter data, by using the appropriate `<input>` element with a `type` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
Always use `type="email"` for email addresses and `type="tel"` for phone numbers.
@@ -39,7 +39,11 @@ Give each form submit button a value that says what it does. Use a clear, recogn
### Use a single name input where possible
-Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.
+Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler. Use `autocomplete="name"` for a single input for name.
+
+```html
+<input type="text" id="fullname" name="fullname" autocomplete="name">
+```
Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.
@@ -63,7 +67,7 @@ Validate data entry both in realtime and before form submission. Use `type="emai
Always use the `<form>` element when you're getting users to enter data
-Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-in for older browsers, and can still work even if JavaScript fails.
+Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screen readers and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-in for older browsers, and can still work even if JavaScript fails.
### Don't double up inputs
@@ -94,7 +98,7 @@ You can help browsers store data correctly and autofill inputs, so users don't h
1. The `autocomplete`, `name`, `id`, and `type` attributes help browsers understand the role of inputs in order to store data that can later be used for autofill. To allow data to be stored for autofill, modern browsers also require inputs to have a stable `name` or `id` value (not randomly generated on each page load or site deployment), and to be in a `<form>` element with a `submit` button.
1. The `autocomplete` attribute helps browsers correctly autofill inputs using stored data.
-For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` value to help browsers differentiate between new and current passwords.
+For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` value to help browsers differentiate between new and current passwords (`autocomplete="new-password"` and `autocomplete="current-password"` respectively).
### Use autocomplete="current-password" for an existing password
diff --git a/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md b/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md
index 251fbac..1e1e8df 100644
--- a/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md
+++ b/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md
@@ -23,7 +23,7 @@ To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a
### Make the most of HTML attributes
-Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
+Make it easy for users to enter data, by using the appropriate `<input>` element with a `type` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.
Always use `type="email"` for email addresses and `type="tel"` for phone numbers.
@@ -39,7 +39,11 @@ Give each form submit button a value that says what it does. Use a clear, recogn
### Use a single name input where possible
-Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.
+Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler. Use `autocomplete="name"` for a single input for name.
+
+```html
+<input type="text" id="full-name" name="ful-name" autocomplete="name">
+```
Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.
@@ -63,7 +67,7 @@ Validate data entry both in realtime and before form submission. Use `type="emai
Always use the `<form>` element when you're getting users to enter data
-Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-up for older browsers, and can still work even if JavaScript fails.
+Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screen readers and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-up for older browsers, and can still work even if JavaScript fails.
### Don't double up inputs
@@ -73,7 +77,7 @@ Some sites force users to enter emails or passwords twice. That might reduce err
Passwords inputs should have `type="password"` to hide password text and help the browser understand that the input is for passwords. (Note that browsers use a variety of techniques to understand input roles and decide whether or not to offer to save passwords.)
-You should add a **Show password** toggle to enable users to check the text they've entered—and don't forget to add a **Forgot password** link.
+You should add a **Show password** toggle to enable users to check the text they've entered.
### Give mobile users the right keyboard
diff --git a/skills/modern-web-guidance/guides/forms/brand-consistent-forms.md b/skills/modern-web-guidance/guides/forms/brand-consistent-forms.md
index acec222..90eaf44 100644
--- a/skills/modern-web-guidance/guides/forms/brand-consistent-forms.md
+++ b/skills/modern-web-guidance/guides/forms/brand-consistent-forms.md
@@ -65,7 +65,7 @@ body {
- **DO** use `accent-color` to easily theme form controls to match your brand.
- **DO NOT** blindly trust the browser to handle contrast. While browsers are supposed to automatically determine an eligible contrast color, known bugs in implementations like **Safari** (WebKit bug 244233) and **Android Chrome** (Chromium bug 343503163) can fail to invert checkmark colors, leading to invisible or hard-to-see controls when using colors that lack sufficient contrast against the background (e.g., light colors in light mode, or dark colors in dark mode).
- **DO** combine `accent-color` with `color-scheme: light dark` to ensure form controls look good in both light and dark themes.
-- **DO NOT** use a color that is too close to the background color, even though browsers try to guarantee contrast, it's best to provide a color with good base contrast.
+- **DO NOT** use a color that is too close to the background color, even though browsers try to guarantee contrast, it's best to provide a color with good base contrast (at least `3:1` with the background color).
- **DO NOT** assume `accent-color` works on all form elements. Currently, it only tints `checkbox`, `radio`, `range`, and `progress` elements.
## Fallback Strategy
diff --git a/skills/modern-web-guidance/guides/forms/branded-select-styling.md b/skills/modern-web-guidance/guides/forms/branded-select-styling.md
index ec7533f..658d240 100644
--- a/skills/modern-web-guidance/guides/forms/branded-select-styling.md
+++ b/skills/modern-web-guidance/guides/forms/branded-select-styling.md
@@ -86,7 +86,7 @@ The following example demonstrates a custom select styled with a monospace font
- **DO** use `appearance: base-select` when your design system requires high-fidelity, visual consistency across all form controls that cannot be achieved with standard cross-browser select overrides.
- **DO NOT** use this if you rely on the operating system's native picker experience (e.g., the standard scroll wheel picker on iOS devices). Opting into `base-select` opts out of native mobile UI controls in favor of web-rendered top-layer menus.
-- **DO** verify that color contrast meets WCAG standards. The customizable picker allows you to set ad-hoc colors, but you are responsible for ensuring text remains legible against custom backgrounds.
+- **DO** verify that color contrast meets WCAG standards (at least `3:1` with the background color). The customizable picker allows you to set ad-hoc colors, but you are responsible for ensuring text remains legible against custom backgrounds.
- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
- Use standard `value` attributes on options to ensure form submission works exactly as before.
diff --git a/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md b/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
index 9dcbc64..324bec6 100644
--- a/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
+++ b/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
@@ -64,7 +64,7 @@ To style the selected *option*, use `option:checked`. For example:
}
```
-As with any UI control, do not communicate state with color alone, and use multiple visual indicators (e.g. colors, border thickness, checkmark) to communicate which option is selected.
+As with any UI control, do not communicate state with color alone, and use multiple visual indicators (e.g. colors, border thickness, checkmark) to communicate which option is selected. Ensure that at least one of the visual indicators to indicate the selected state has a contrast of at least 3:1 with the background color.
### 5. (Optional) Style the selected option checkmark
@@ -118,7 +118,7 @@ Do NOT use `padding-inline-start` or `padding-block-end` for this, as they will
By default, the `<select>` will show a text-only version of the selected option.
To display rich content for the selected value, use `<selectedcontent>` inside a `<button>` and/or to display the selected option differently (e.g. hide certain details).
-Not **NOT** use `<selectedcontent>` without the `<button>` around it, as the `<selectedcontent>` will just become part of the picker, like any other content element.
+**DO NOT** use `<selectedcontent>` without the `<button>` around it, as the `<selectedcontent>` will just become part of the picker, like any other content element.
### Best practices
@@ -128,19 +128,18 @@ Not **NOT** use `<selectedcontent>` without the `<button>` around it, as the `<s
## Accessibility
-<!-- See https://github.com/GoogleChrome/modern-web-guidance-src/pull/960#pullrequestreview-4880620093 -->
-
A native `<select>` only handles linear Up/Down arrow navigation, so Left/Right do nothing in the open picker and Up/Down still navigate items sequentially, regardless of rows and columns.
-To implement spatial navigation that follows the grid, you can intercept `keydown` and route focus to the nearest option in the pressed direction (e.g. using `getBoundingClientRect()`) when arrow keys are used.
+To add horizontal navigation that follows the grid, you can intercept `keydown` for the `Left` and `Right` arrow keys and route focus to the nearest option in the pressed direction (e.g. using `getBoundingClientRect()`).
To determine the appropriate next/previous item, use DOM methods that operate on actual geometry (e.g. `getBoundingClientRect()`) rather than parsing CSS strings like `grid-template-columns` or `grid-column`, which can be brittle and error-prone for complex grids, subgrid, RTL, and other layout scenarios.
That said, do not unnecessarily overengineer; use what invariants you know are true about the layout to simplify this logic.
**Note:** This _only_ addresses keyboard navigation. The `<select>` and its `::picker()` still have their default roles (`menu` or `listbox`), and these cannot be overridden, nor are they allowed to contain an element with `role="grid"`.
-Nesting a wrapper with `role="grid"` inside the picker works in practice, but is not valid, and may surprise AT users.
-In some cases, using `<optgroup>` to group options may produce a good screen reader UX without `role="grid"`.
+It is not valid to apply grid semantics in a `::picker()` pseudo-element as it's against its content model.
+Because grid roles will not be conveyed to screen reader users, ensure that the `Down` and `Up` arrow keys still move focus sequentially to the next and previous item respectively (for example, by flowing the grid in columns or grouping columns with `<optgroup>`), even when `Left` and `Right` have been scripted, so screen reader users visit all options in the list.
Otherwise, it may be ultimately necessary to switch to a custom solution using the popover API, anchor positioning, and `role="grid"` to achieve the desired UX for screen reader users.
+Ensure that the focus indicator when moving through the options has a contrast of at least 3:1 with the background color or adjacent color.
## Fallback Strategy
diff --git a/skills/modern-web-guidance/guides/forms/forms.md b/skills/modern-web-guidance/guides/forms/forms.md
index 0409c17..70ade72 100644
--- a/skills/modern-web-guidance/guides/forms/forms.md
+++ b/skills/modern-web-guidance/guides/forms/forms.md
@@ -5,70 +5,93 @@
### Guidelines
- **DO** use the `<form>` element to wrap interactive controls for data collection.
+- **DO** wrap search forms and filtering controls in a `<search>` element.
+- **DO** give `<form>` elements an accessible name via `aria-labelledby` (pointing to the form's heading) when a page has multiple forms.
- **DO** use `method="POST"` for sensitive data and mutations; use `method="GET"` for idempotent requests (e.g., search).
- **DO** specify the `action` attribute for the destination URL.
- **DO** specify a `name` attribute for every form control to identify data on submission.
-- **DO** use semantic tags like `<button type="submit">`, `<textarea>`, and `<select>`.
-- **DO** use `<fieldset>` and `<legend>` to group related controls.
+- **DO** use semantic tags like `<button type="submit">`, `<textarea>`, `<select>`, and specific `<input>` types.
+- **DO** explicitly set `type="button"` on secondary or helper buttons so they don't default to type="submit".
+- **DO** use `<fieldset>` and `<legend>` (with `<legend>` as the first child) to group related controls. **DON'T** use `<fieldset>` for visual styling without a `<legend>`
- **DO** use actionable language on submit buttons (e.g., "Save changes").
+- **DON'T** nest `<form>` elements inside other `<form>` elements.
- **DON'T** use `GET` for sensitive data (it exposes data in history/logs).
-- **DON'T** use generic `<div>` or `<span>` for form controls.
+- **DON'T** use generic `<div>`, `<span>`, or `<a>` elements for form controls.
- **DON'T** use `type="button"` for primary submission buttons.
- **DON'T** disable textarea resizing without alternate layout provisions.
+- **DON'T** use CSS to visually reorder form controls away from their DOM/keyboard `Tab` order.
+- **DON'T** auto-submit a form when a user changes `<select>`, radio buttons, or checkbox without an explicit submit action.
### Code Example
```html
-<form action="/search" method="GET">
- <fieldset>
- <legend>Search Preferences</legend>
- <label for="q">Query:</label>
- <input type="text" id="q" name="q" required>
+<search>
+ <form action="/search" method="GET">
+ <label for="q">Search query</label>
+ <input type="search" id="q" name="q">
+
+ <fieldset>
+ <legend>Search filters</legend>
+ <input type="checkbox" id="exact" name="exact" value="true">
+ <label for="exact">Exact match only</label>
+ <input type="checkbox" id="archived" name="archived" value="true">
+ <label for="archived">Include archived results</label>
+ </fieldset>
+
<button type="submit">Search</button>
- </fieldset>
-</form>
+ </form>
+</search>
```
### Selection Control Decision Matrix
| Options Count | Choice Type | Recommended Element | Usability & Accessibility Logic |
| :--- | :--- | :--- | :--- |
-| **1–5** | Single (Exclusive) | `<input type="radio">` | **Zero-click scanning**: All choices are immediately visible. Faster scan time. |
+| **1** | Binary toggle (Yes/No) | `<input type="checkbox">` | **Reversible State**: Can be checked and unchecked with space unlike a radio button, which gets stuck once checked. |
+| **2–5** | Single (Exclusive) | `<input type="radio">` | **Zero-click scanning**: All choices are immediately visible. Faster scan time. |
| **6+** | Single (Exclusive) | `<select>` | **Space conservation**: Use only when vertical space is premium or the list is long. |
| **10+ / Dynamic** | Single (Exclusive) | `<input list="id">` (`<datalist>`) | **Fuzzy Search**: Prevents scrolling fatigue in massive sets (e.g., countries). |
-| **Any** | Multi-select | `<input type="checkbox">` | **Standard semantics**: Native non-exclusive toggles. |
+| **2+** | Multi-select | `<input type="checkbox">` | **Standard semantics**: Native non-exclusive toggles. |
-**Single-Sentence Mental Model**: "Expose mutually exclusive options as visible radio buttons when choices are fewer than six; use `<select>` only when space is constrained or the list is long."
+**Single-Sentence Mental Model**: "Expose 2 to 5 mutually exclusive options as visible radio buttons when choices are fewer than six; use `<select>` only when space is constrained or the list is long."
## 2. Accessible Labeling and State
### Guidelines
- **DO** always associate `<label>` with its input using `for` and `id`.
-- **DO** place labels above form controls to enable faster scanning.
-- **DO** use visible labels; do not rely on `placeholder` alone.
+- **DO** place `<label>` elements before text inputs, `<textarea>`, and `<select>` controls in the DOM and stack them visually above the control for faster scanning.
+- **DO** place `<label>` elements inline immediately after `<input type="checkbox">` and `<input type="radio">` controls for consistent alignment.
+- **DO** use visible labels and keep critical format instructions (e.g., `3-12 characters`) in the label or persistent helper text; do not rely on `placeholder` alone.
- **DO** ensure the vertical margin between a label and its input is less than the margin between form groups (**Gestalt Proximity Rule**).
+- **DO** set `aria-invalid="true"` on form controls that fail custom validation, and clear it once resolved.
- **DO** use `aria-describedby` to link inputs with help text or error messages.
- **DO** define the `lang` attribute on `<html>` for proper device translation.
- **DO** use non-color visual cues (icons, text) to communicate state (don't rely on color alone).
-- **DO** indicate clearly which fields are required.
+- **DO** indicate clearly which fields are required both visually in the label and programmatically with the `required` attribute.
- **DO** use `aria-live` for dynamic error announcements.
-
-- **DON'T** use `placeholder` as a replacement for labels.
-- **DON'T** use `aria-label` as the sole text description if translation is needed.
-- **DON'T** disable focus outlines without providing a high-contrast alternative.
+
+- **DON'T** use `aria-label` when a visible `<label>` can be used or override visible text with a mismatched `aria-label`.
### Code Example
```html
<div class="field">
- <label for="username">Username:</label>
+ <label for="username">Username: <span aria-hidden="true">*</span></label>
<input type="text" id="username" name="username" aria-describedby="user-help" required>
<span id="user-help" class="hint">3-12 characters.</span>
</div>
<style>
+ .field {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.25rem;
+ margin-block-end: 1.5rem;
+ }
+
input:focus-visible {
outline: 3px solid #0b57d0;
outline-offset: 2px;
@@ -83,20 +106,22 @@
- **DO** use the `autocomplete` attribute to specify expected data (e.g., `email`, `tel`, `current-password`, `new-password`).
- **DO** use `inputmode` to optimize on-screen keyboards (e.g., `inputmode="numeric"` for PINs).
- **DO** use `enterkeyhint` to set the Enter key label (e.g., `next`, `done`).
-- **DO** turn off text correction on fields that hold identifiers rather than prose: `autocorrect="off"` (plus `autocapitalize="off"` and `spellcheck="false"`) on usernames, emails, URLs, codes, and search inputs. Leave the defaults on for free-text fields like messages and comments.
+- **DO** turn off text correction on fields that hold identifiers rather than prose: `autocorrect="off"` (plus `autocapitalize="none"` and `spellcheck="false"`) on usernames, emails, URLs, codes, and search inputs. Leave the defaults on for free-text fields like messages and comments.
- **DO** use single-field inputs for complex numbers (credit cards, phones) to help autofill.
- **DO** use a single `<input type="text" inputmode="numeric" autocomplete="one-time-code">` and the WebOTP API for SMS one-time passcode verification. See guide `sms-otp-form` (via `npx -y modern-web-guidance@latest retrieve "sms-otp-form"`).
- **DON'T** use `type="number"` for credit cards, ZIP codes, or one-time passcodes (causes UI scroll issues and removes leading zeros).
+- **DON'T** split a single value (such as a 6-digit OTP, phone number, or credit card) across multiple `<input>` boxes that auto-advance focus on keypress. Instead, use `type="text"` with `inputmode="numeric"` (`type=number` adds spinner buttons). If needed, styling can convey a similar UI. JS can set a `--value-length` CSS variable for higher fidelity styling that resembles these inputs, without their usability and accessibility issues.
+- **DON'T** block copy-and-paste (`paste` events) or disable `autocomplete` on passwords, verification codes, or other authentication fields.
### Code Example
```html
<label for="zip">ZIP Code:</label>
-<input type="text" id="zip" name="zip" autocomplete="postal-code" inputmode="numeric" pattern="\d{5}">
+<input type="text" id="zip" name="zip" autocomplete="postal-code" inputmode="numeric" pattern="\d{5}" enterkeyhint="next">
<label for="username">Username:</label>
-<input type="text" id="username" name="username" autocomplete="username" autocorrect="off" autocapitalize="off" spellcheck="false">
+<input type="text" id="username" name="username" autocomplete="username" autocorrect="off" autocapitalize="none" spellcheck="false" enterkeyhint="done">
```
## 4. Constraints and Validation
@@ -104,10 +129,13 @@
### Guidelines
- **DO** use native constraints: `required`, `minlength`, `maxlength`, `pattern`.
-- **DO** use CSS pseudo-classes `:invalid:user-invalid` for non-intrusive styling.
-- **DO** use the ValidityState API (`setCustomValidity`) for custom messaging.
+- **DO** use CSS pseudo-classes `:user-invalid` for non-intrusive styling.
+- **DO** use the ValidityState API (`setCustomValidity`) for custom messaging and write clear error messages that explain how to fix the issue.
+- **DO** move focus to the first invalid field (or an error summary) when a form submission fails validation.
+- **DON'T** use the raw `:invalid` CSS pseudo-class alone for error styling to ensure empty required fields are not marked as invalid before the user interacts with the form.
- **DON'T** disable submit buttons to block validation; let users submit and highlight errors. However, **DO** disable the button *after* a valid submission is clicked to prevent double-posts.
+- **DON'T** trigger validation errors or `aria-live` error announcements on every keystroke while the user is typing (validate on submit or `blur`, and clear errors on `input` once resolved).
### Code Example
@@ -131,10 +159,10 @@
| Event Trigger | Phase | Action Allowed | UX / Accessibility Logic |
| :--- | :--- | :--- | :--- |
| **`input`** | Active Typing | **Clear** existing errors only. | **Non-intrusive**: Do not yell at the user before they finish typing. |
-| **`blur` / `focusout`** | Exiting Field | **Run** check and show error. | **Contextual validation**: Validate once the user indicates they are "done" with a field. |
-| **`submit`** | Final Attempt | **Block** and route focus. | **Final gatekeeper**: Intercepts bad payloads and forces screen reader focus to the summary. |
+| **`blur` / `focusout`** | Exiting Field | **Run** check (if edited) and show error. | **Contextual validation**: Validate once the user indicates they are "done" with a field. |
+| **`submit`** | Final Attempt | **Block** and route focus. | **Final gatekeeper**: Intercepts bad payloads and moves keyboard and screen reader focus to the first invalid field or an error summary. |
-**Single-Sentence Mental Model**: "Validate on `blur` to avoid premature warnings while typing, and reset error states on `input` as soon as the user attempts a correction."
+**Single-Sentence Mental Model**: "Validate on `blur` (if edited) to avoid premature warnings while typing, and reset error states on `input` as soon as the user fixes the value, and route the focus to the first error or summary on `submit`."
**Security vs UX Scale**: Client-side validation is for User Experience; Server-side validation is for Security. Never treat browser constraints as a data integrity defense.
@@ -143,7 +171,7 @@
### Guidelines
- **DO** use single-column layouts for scanning.
-- **DO** set `font-size` to at least `1rem` (16px) to prevent iOS zoom.
+- **DO** set `font: inherit` and `font-size: max(1rem, 1em)` on form controls to scale with larger containers while staying at least `1rem`(16px) to prevent iOS zoom.
- **DO** expand clickable areas for mobile tap targets using padding tricks.
- **DO** ensure tap targets are at least `48px`.
- **DO** use units relative to root (`rem`) and unitless `line-height`.
@@ -164,7 +192,8 @@ label {
}
input {
- font-size: 1rem;
+ font: inherit;
+ font-size: max(1rem, 1em);
padding: 0.75rem;
min-height: 48px;
box-sizing: border-box;
@@ -183,7 +212,8 @@ input {
- **DO** use `accent-color` for quick branding of native radios/checkboxes.
- **DO** use `appearance: none` for custom dropdown arrows without breaking semantics.
-- **DO** ensure inputs are clearly visible with adequate border contrast (e.g., `#ccc` or darker on white backgrounds).
+- **DO** ensure inputs are clearly visible with adequate border contrast (e.g., `#767676` or darker on white backgrounds).
+- **DO** maintain a visible `:focus-visible` indicator on all controls. Never disable focus outlines (`outline:none`) without providing a high-contrast alternative.
- **DO** hide inputs visually using the canonical `.visually-hidden` recipe (`clip-path: inset(50%)` with 1px dimensions) — NOT `display: none`, which removes them from the accessibility tree.
### Code Example
@@ -211,7 +241,7 @@ input {
display: inline-block;
width: 1.25rem;
height: 1.25rem;
- border: 2px solid #ccc;
+ border: 2px solid #767676;
}
input:focus-visible + .checkbox-label::before {
outline: 2px solid #0b57d0;
@@ -226,6 +256,7 @@ input {
- **DO** check `KeyboardEvent.isComposing` before treating the `Enter` key as a submit action in chat or text inputs to ensure IME text composition is not interrupted. See guide `ime-safe-enter-submit` (via `npx -y modern-web-guidance@latest retrieve "ime-safe-enter-submit"`).
- **DO** prevent default navigation on form submit for AJAX (`e.preventDefault()`).
- **DO** use `ValidityState` interfaces for real-time validation checks.
+- **DO** announce AJAX submission results via `role="status"` or `aria-live`.
- **DO** use `aria-expanded` and `aria-controls` for dynamic UI reveals.
- **DON'T** block page submission if JS fails; ensure server-side fallback.
@@ -246,13 +277,13 @@ form.addEventListener('submit', (e) => {
- **DO** use `autocomplete="new-password"` for sign-up and `autocomplete="current-password"` for sign-in.
- **DO** allow pasting into password fields.
-- **DO** provide a toggle capability allowing users to unmask password input.
+- **DO** provide an accessible toggle `<button type="button">` with `aria-pressed` allowing users to unmask password input.
- **DO** indicate exact amounts on pay buttons (e.g., "Pay $100").
- **DO** use `autocomplete="cc-number"`, `cc-exp`, `cc-csc`.
- **DO** use HTTPS for all pages.
- **DO** implement cryptographically secure anti-CSRF tokens for mutating actions (POST/PUT/DELETE).
- **DO** sanitize user input (e.g., via DOMPurify) before injecting it into the DOM to prevent XSS.
-- **DO** implement spam protection (honeypots or CAPTCHA) for open forms.
+- **DO** implement spam protection for open forms using accessible CAPTCHAs (e.g., invisible reCAPTCHA) or honeypot fields hidden from assistive tech (`tabindex="-1"` and `aria-hidden="true"`)
- **DON'T** utilize HTTP `GET` for endpoints executing state changes.
- **DON'T** use inline JavaScript (e.g., `onclick="..."`) directly within form markup to satisfy strict Content Security Policies (CSP).
@@ -286,7 +317,7 @@ form.addEventListener('submit', (e) => {
<div id="password-constraints">Eight or more characters.</div>
</div>
- <button id="sign-up">Sign up</button>
+ <button id="sign-up" type="submit">Sign up</button>
</form>
```
@@ -299,6 +330,7 @@ form.addEventListener('submit', (e) => {
- **DO** use `autocomplete="street-address"`.
- If the site has users in different countries, **DO** use the `<textarea>` element for addresses, to accommodate different address formats in different geographical regions. If the form uses separate inputs for address parts (e.g. Street, City), **DO** use `autocomplete` values `address-line1`, `address-line2`, etc.
- **DO** make postal codes optional.
+- **DO** provide a "Same as shipping address" checkbox when collecting both shipping and billing addresses (and scope `autocomplete` with `shipping` or `billing` inside a `<fieldset>`).
- **DON'T** split name inputs into rigid variables ("First", "Last") for global audiences.
- **DON'T** enforce Latin-only characters for names and usernames.
@@ -328,7 +360,7 @@ form.addEventListener('submit', (e) => {
### Guidelines
- **DO** test forms across multiple devices, browsers, and screen sizes.
-- **DO** test keyboard-only navigation (using `Tab` and `Shift+Tab`) and verify visual focus.
+- **DO** test keyboard-only navigation (using `Tab`, `Shift+Tab`, `Space`, `Enter`, and Arrow keys) and verify visual focus.
- **DO** emulate various impairments (visual, motor) using browser tools.
- **DO** use analytics to monitor form completion rates and bounce points.
- **DO** track discrete events (e.g., field focus, click) to find micro-friction points.
@@ -359,17 +391,20 @@ form.addEventListener('submit', (e) => {
### Guidelines
-- **DO** clearly display progress through a multi-page form with clear labels and progress indicators.
-- **DO** allow users to navigate backwards and forwards between pages.
+- **DO** clearly display progress through a multi-page form with clear labels and accessible progress indicators (e.g., `aria-current="step"` or `<progress>`).
+- **DO** allow users to navigate backwards and forwards between pages without losing previously entered data.
+- **DO** move focus to the new step's heading (`tabindex="-1"`) or first input when transitioning between steps dynamically without a full page reload.
- **DO** use context-specific `enterkeyhint` values (e.g., `"previous"`, `"next"`) to guide navigation via on-screen keyboards.
- **DO** design layouts so that the mobile keyboard does not obscure inputs or buttons (e.g., by placing them in the upper half of the viewport when focused or using CSS scroll-padding).
+- **DON'T** leave inactive wizard steps in the keyboard `Tab` order or accessibility tree (use `hidden`, `display: none`, or `inert` on non-active steps).
+
### Code Example
```html
<nav aria-label="Progress">
<ol class="progress-tracker">
- <li class="step-done">Step 1: Account</li>
+ <li class="step-done">Step 1: Account (completed)</li>
<li class="step-active" aria-current="step">Step 2: Shipping</li>
<li class="step-todo">Step 3: Payment</li>
</ol>
diff --git a/skills/modern-web-guidance/guides/forms/required-field-feedback.md b/skills/modern-web-guidance/guides/forms/required-field-feedback.md
index 6235172..f136a4b 100644
--- a/skills/modern-web-guidance/guides/forms/required-field-feedback.md
+++ b/skills/modern-web-guidance/guides/forms/required-field-feedback.md
@@ -13,6 +13,8 @@ The `:user-invalid` pseudo-class solves this perfectly. For a required field, it
1. **HTML Constraint**: Add the `required` attribute to your inputs.
2. **Visual Feedback**: Use `:user-invalid` to style the border red and show a "Required" helper text.
3. **Timing**: Rely on the browser's native timing for visual feedback. You don't need `onBlur` handlers to add a `touched` class anymore, though some JavaScript is still needed to sync ARIA attributes (see below).
+4. **Error Text**: Show visible error text with the error styling, so the error isn't shown by color alone. Start each message with an error icon that has a text alternative such as "Error" (the safest choice), or word every message as an error, for example "Name is required.", and use the same approach for every error in the form.
+5. **Error Link**: List the error message in the field's `aria-describedby` only while the field is invalid, so screen readers read it with the field. A reference in the markup would read the hidden message from page load. The script in section 3 does this for each field whose `data-error` attribute is set to its error message's `id`.
## Implementation Guide
@@ -21,16 +23,17 @@ The `:user-invalid` pseudo-class solves this perfectly. For a required field, it
<form id="feedback-form">
<div class="field">
<label for="full-name">Full Name</label>
+ <!-- Set data-error to the error message's id. The aria-invalid script lists that id in aria-describedby while the field is invalid. -->
<input
type="text"
id="full-name"
name="full-name"
required
- aria-errormessage="name-error"
+ data-error="name-error"
>
<!-- MANDATORY: Include an icon or distinct non-color indicator alongside error text -->
<div id="name-error" class="error-msg">
- <span aria-hidden="true">❌</span> This field is required.
+ <span role="img" aria-label="Error">❌</span> This field is required.
</div>
</div>
</form>
@@ -46,7 +49,7 @@ The `:user-invalid` pseudo-class solves this perfectly. For a required field, it
}
/*
- Only highlight empty required fields AFTER the user visits them.
+ Only highlight empty required fields AFTER the user interacts with them or attempts submission.
MANDATORY: Provide multiple indicators (border shift + helper text/icon) to avoid color-only state communication.
*/
input:user-invalid {
@@ -67,37 +70,126 @@ input:required:user-valid {
### 3. JavaScript State Synchronization
-MANDATORY: Because `:user-invalid` is a visual state, you MUST provide a JavaScript bridge to sync `aria-invalid="true"` dynamically for assistive technologies when a user blurs an invalid field or attempts submission.
+MANDATORY: Because `:user-invalid` is a visual state, you MUST provide a JavaScript bridge to sync `aria-invalid="true"` dynamically for assistive technologies when a user blurs an invalid field or attempts submission, deriving it from `:user-invalid`, not `checkValidity()`, which is already false when a user tabs through an untouched field.
+
+Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
+
+* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
+* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
+* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.
```javascript
-const form = document.getElementById('feedback-form');
+// List the field's error message (the id in data-error) in aria-describedby only while
+// it's shown: text that aria-describedby references is announced even when it's hidden.
+const linkError = (el, shown) => {
+ const errorId = el.dataset.error;
+ if (!errorId) return;
+ const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
+ else el.removeAttribute('aria-describedby');
+};
-const syncAriaInvalid = (input) => {
- if (!input.checkValidity()) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+// One polite live region for the page announces an error that appears when the user
+// leaves or changes a field. Run this once the form is in the page.
+const announcer = document.createElement('div');
+announcer.setAttribute('aria-live', 'polite');
+announcer.classList.add('visually-hidden');
+document.body.append(announcer);
+let announceTimer;
+let announcedField;
+
+// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
+const spokenText = (node) => {
+ const copy = node.cloneNode(true);
+ copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
+ copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
+ return copy.textContent.replace(/\s+/g, ' ').trim();
+};
+const announceError = (el) => {
+ const error = document.getElementById(el.dataset.error);
+ if (!error) return;
+ const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ announcedField = el;
+ // Wait until the screen reader has announced the field that receives focus next.
+ announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
};
-// Sync on blur when a user finishes interacting
-form.addEventListener('blur', (e) => {
- if (e.target.matches('input[required]')) {
- syncAriaInvalid(e.target);
+// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
+// an aria-invalid="true" that this script didn't set (for example from a server check)
+// is left alone.
+const flagged = new WeakSet();
+// Fields whose current error has been announced, or read out by focus after a failed
+// submit. A field can become invalid while the user types, so this is tracked separately.
+const announced = new WeakSet();
+const syncAria = (el, announce = false) => {
+ if (!el.matches?.('input, select, textarea')) return;
+ const invalid = el.matches(':user-invalid');
+ if (invalid) {
+ if (announce && !announced.has(el)) {
+ announceError(el);
+ announced.add(el);
+ }
+ el.setAttribute('aria-invalid', 'true');
+ linkError(el, true);
+ flagged.add(el);
+ } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
+ el.setAttribute('aria-invalid', 'false');
+ linkError(el, false);
+ flagged.delete(el);
+ announced.delete(el);
+ // Clear a fixed field's announcement so it isn't found later when reading the page.
+ if (announcedField === el) {
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ }
}
-}, true);
+};
-// Sync all required fields when submission is attempted
-form.addEventListener('submit', () => {
- form.querySelectorAll('input[required]').forEach(syncAriaInvalid);
-});
+// Start every field at aria-invalid="false".
+document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));
-// Remove error state immediately upon correction
-form.addEventListener('input', (e) => {
- if (e.target.matches('input[required]') && e.target.checkValidity()) {
- e.target.removeAttribute('aria-invalid');
- }
+// Update on blur (to show and announce an error) and input (to clear it)
+document.addEventListener('blur', (e) => syncAria(e.target, true), true);
+document.addEventListener('input', (e) => {
+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});
+
+// Checkboxes, radio buttons and other controls that commit on 'change' can become
+// :user-invalid without losing focus, so update on change too.
+document.addEventListener('change', (e) => syncAria(e.target, true), true);
+
+// A failed submit fires 'invalid' on each failing field, including required fields the
+// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
+// first invalid field announces its error, so these aren't announced.
+document.addEventListener('invalid', (e) => {
+ announced.add(e.target);
+ syncAria(e.target);
+}, true);
+
+// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
+document.addEventListener('reset', (e) => {
+ setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
+}, true);
+```
+
+Hide the live region with the `.visually-hidden` utility:
+
+```css
+/* Hides content visually but keeps it in the accessibility tree */
+.visually-hidden:where(:not(:focus-within, :active)) {
+ position: absolute !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ width: 1px !important;
+ height: 1px !important;
+ margin: -1px !important;
+ padding: 0 !important;
+ border: 0 !important;
+ white-space: nowrap !important;
+}
```
## Fallbacking & Browser Support
@@ -110,14 +202,15 @@ Supported by: Chrome 119 (Oct 2023), Edge 119 (Nov 2023), Firefox 88 (Apr 2021),
### CSS for Fallback
```css
-input:user-invalid,
-input.user-invalid-fallback {
+/* Applies to every field that can be invalid (input, select, textarea). :is() keeps the
+ rule working where :user-invalid isn't supported: in a plain selector list, one
+ unsupported selector drops the whole rule. */
+:is(:user-invalid, .user-invalid-fallback) {
border-color: #d93025;
background-color: #fce8e6;
}
-input:user-invalid + .error-msg,
-input.user-invalid-fallback + .error-msg {
+:is(:user-invalid, .user-invalid-fallback) + .error-msg {
display: block;
}
```
@@ -131,17 +224,26 @@ const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
- const isValid = input.checkValidity();
+ // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
+ const isValid = input.validity.valid;
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
- if (!isValid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+ input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
+ linkError(input, !isValid);
+ };
+
+ // List the error message (the id in data-error) in aria-describedby only while it's
+ // shown: text that aria-describedby references is announced even when it's hidden.
+ const linkError = (input, shown) => {
+ const errorId = input.dataset.error;
+ if (!errorId) return;
+ const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
+ else input.removeAttribute('aria-describedby');
};
const handleEvent = (event) => {
@@ -153,13 +255,22 @@ const UserInvalidFallback = (() => {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
- control.removeAttribute('aria-invalid');
+ if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
+ if (control.dataset?.error) linkError(control, false);
}
return;
}
if (!input.checkValidity) return;
+ // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
+ // field, including required fields the user never touched, so flag them all.
+ if (event.type === 'invalid') {
+ dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
+ updateState(input);
+ return;
+ }
+
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasInteracted = true;
@@ -180,9 +291,15 @@ const UserInvalidFallback = (() => {
const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
+ // Firefox and Safari expose an empty required field as invalid from page load.
+ root.querySelectorAll('input, select, textarea').forEach((el) => {
+ if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
+ });
+
root.addEventListener('blur', handleEvent, true); // Capture phase
root.addEventListener('input', handleEvent);
root.addEventListener('change', handleEvent);
+ root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
root.addEventListener('reset', handleEvent, true); // Capture resets
};
@@ -196,19 +313,5 @@ UserInvalidFallback.init(form);
## Other Considerations
-1. **Asterisks**: It is still best practice to indicate required fields visually (e.g., with an asterisk `*`) in the label, so users know what to expect *before* they interact.
+1. **Asterisks**: It is still best practice to indicate required fields visually (e.g., with an asterisk `*`) in the label, so users know what to expect *before* they interact. Explain the asterisk once before the form (for example, "Fields marked * are required."), and wrap it in `<span aria-hidden="true">*</span>`, because the `required` attribute already makes screen readers announce "required".
2. **Submit Buttons**: Unlike `disabled` buttons, keep your submit button enabled. If the user clicks it, the browser will automatically trigger `:user-invalid` on all empty required fields and focus the first one. This is excellent for accessibility and UX.
-3. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
-
-```javascript
-// Sync aria-invalid with the CSS :user-invalid state
-const syncAria = (el) => {
- el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
-};
-
-// Update on blur (to show error) and input (to clear it)
-document.addEventListener('blur', (e) => syncAria(e.target), true);
-document.addEventListener('input', (e) => {
- if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
-});
-```
diff --git a/skills/modern-web-guidance/guides/forms/rich-media-picker.md b/skills/modern-web-guidance/guides/forms/rich-media-picker.md
index 78e087f..fd71324 100644
--- a/skills/modern-web-guidance/guides/forms/rich-media-picker.md
+++ b/skills/modern-web-guidance/guides/forms/rich-media-picker.md
@@ -21,7 +21,7 @@ To implement a rich media picker using the Customizable Select API:
</button>
<!-- Define concise aria-label values on options whose mirrored rich content would otherwise read awkwardly as a concatenated string -->
- <option value="frontend" aria-label="Frontend Developer">
+ <option value="frontend">
<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
</svg>
@@ -31,7 +31,7 @@ To implement a rich media picker using the Customizable Select API:
</div>
</option>
- <option value="backend" aria-label="Backend Developer">
+ <option value="backend">
<svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="2" y="12" width="20" height="14" rx="2" ry="2"></rect>
</svg>
@@ -85,7 +85,7 @@ select.custom-select option:hover {
}
/* Remove standard OS checkmark for base-select */
-select.custom-select option::before {
+select.custom-select option::checkmark {
display: none;
}
@@ -103,12 +103,63 @@ select.custom-select option:checked .option-title {
- **DO** use `appearance: base-select` when you need complex options layouts (icons, descriptions, images) that was previously only possible with heavy JavaScript UI frameworks.
- **DO NOT** use ad-hoc elements if you notice performance lags; the browser handles native keyboard focus natively.
-- **DO** account for top-layer rendering. The picker renders in the top-layer, meaning it overrides relative `z-index` of page content.
+- **DON'T** use z-index on the picker. The picker renders in the top-layer, meaning it overrides relative `z-index` of page content.
- **DO** hide secondary details (like descriptions) in the button state if they take too much space, by styling `.custom-select selectedcontent .option-desc { display: none; }`.
- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
- Use standard `value` attributes on options to ensure form submission works exactly as before.
+## Accessibility considerations
+
+MANDATORY: When the select is expanded and the list of options are visible, there must be a way to visibly identify which option is selected. Examples of how this could be achieved include: using a custom icon, adding a sufficiently contrasting outline (that clearly differs from focus/hover indication), or using a sufficiently contrasting background color.
+
+Ensure that the rich media picker always has an associated visible label that conveys the context of the information required. This will allow people to independently select the option that they need. This ensures adherence to WCAG 3.3.2 Labels or Instructions, which requires that labels or instructions are provided when content requires user input. Similarly, ensure that all of the options include visible text, and do not rely solely on an image or colour, so that people can easily select the option that they need.
+
+Ensure that options have enough context to be understood in isolation, particularly given that browsers that don't yet support this feature will default to displaying all of the text in a single option. For example, the following rich option, would be rendered as "Frontend Developer React, Vue, CSS", in a browser that doesn't support customizable selects. Without the visual design, this can affect the meaning of the options.
+
+```html
+<!-- Rich options -->
+<option value="frontend">
+ <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round">
+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
+ <line x1="8" y1="21" x2="16" y2="21"></line>
+ <line x1="12" y1="17" x2="12" y2="21"></line>
+ </svg>
+ <div class="option-text">
+ <span class="option-title">Frontend Developer</span>
+ <span class="option-desc">React, Vue, CSS</span>
+ </div>
+</option>
+```
+
+To address this issue, ensure that the content makes sense, regardless of visual styling, and where necessary use inclusively hidden text to ensure that content makes sense. In the previous example, we could add: `<span class="visually-hidden">Responsibilities include:</span>`, as well as a full stop, so that browsers that don't support customizable selects would provide the option text as: "Frontend Developer. Responsibilities include: React, Vue, CSS", which makes more sense. The use of a full stop can help indicate when screen readers should pause when announcing the content, helping people to better understand the structure of the option text. The updated HTML for the option would be:
+
+```html
+<!-- Rich options -->
+<option value="frontend">
+ <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round">
+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
+ <line x1="8" y1="21" x2="16" y2="21"></line>
+ <line x1="12" y1="17" x2="12" y2="21"></line>
+ </svg>
+ <div class="option-text">
+ <span class="option-title">
+ Frontend Developer<span class="visually-hidden">.</span>
+ <span class="visually-hidden">Responsibilities include:</span>
+ </span>
+ <span class="option-desc">React, Vue, CSS</span>
+ </div>
+</option>
+```
+
+This approach helps ensure equity in the information provided across browsers, regardless of whether the feature is supported or not.
+
+**DON'T** override the option's text, by applying an `aria-label` on it. This will result in people missing visible text that hasn't been included in the `aria-label`. It also risks the issue arising when the option text is updated in the future. Instead, ensure that the entire option text makes sense in isolation.
+
+**DON'T** add interactive elements or semantics inside the `<option>` element. People using screen readers will not hear the announcements, and as a result, won't be able to determine that further information is present.
+
## Fallback Strategies
### Fallbacks & browser support for Customizable `<select>`
diff --git a/skills/modern-web-guidance/guides/forms/select-menu-interaction.md b/skills/modern-web-guidance/guides/forms/select-menu-interaction.md
index a783998..248e311 100644
--- a/skills/modern-web-guidance/guides/forms/select-menu-interaction.md
+++ b/skills/modern-web-guidance/guides/forms/select-menu-interaction.md
@@ -1,7 +1,7 @@
# Select Menu Interaction
## The Problem
-For mandatory dropdowns (e.g., "Choose a Country"), standard validation flags the field as invalid immediately if the default option has an empty value. This can create visual noise. We want to show the error only if the user opens the menu and closes it without choosing an option, or attempts to submit the form.
+For mandatory dropdowns (e.g., "Choose a Country"), standard validation flags the field as invalid immediately if the default option has an empty value. This can create visual noise. We want to show the error only after the user has interacted with the menu and left it without choosing an option, or attempts to submit the form without choosing one.
## The Solution
The `:user-invalid` pseudo-class works seamlessly with `<select>` elements. It respects the user's interaction flow: simply loading the page or focusing/blurring without making a change doesn't count as an interaction, so the field stays neutral until they actively attempt a selection.
@@ -10,7 +10,8 @@ The `:user-invalid` pseudo-class works seamlessly with `<select>` elements. It r
1. **HTML Constraint**: Use a `<select>` with `required`. The first option should have `value=""` and ideally be disabled/hidden to force a valid choice.
2. **Visual Feedback**: Use `:user-invalid` to style the select box border.
-3. **Timing**: The browser considers the field "interacted" if the user changes the value (even back to the default invalid state) before they blur the control, or upon form submission.
+3. **Timing**: The browser considers the field "interacted" if the user changes the value (even back to the default invalid state) before they blur the control, or upon form submission. Some browsers also count opening and closing the menu without choosing an option.
+4. **Error Link**: List the error message in the select's `aria-describedby` only while the select is invalid, so screen readers read it with the select. A reference in the markup would read the hidden message from page load. The script in "Accessibility" under Other Considerations does this for each field whose `data-error` attribute is set to its error message's `id`.
## Implementation Guide
@@ -21,11 +22,12 @@ The "placeholder" option is key here.
<form>
<div class="field">
<label for="country">Country</label>
+ <!-- Set data-error to the error message's id. The aria-invalid script lists that id in aria-describedby while the select is invalid. -->
<select
id="country"
name="country"
required
- aria-errormessage="country-error"
+ data-error="country-error"
>
<option value="" disabled selected>Select a country...</option>
<option value="us">United States</option>
@@ -33,7 +35,7 @@ The "placeholder" option is key here.
<option value="uk">United Kingdom</option>
</select>
<div id="country-error" class="error-msg">
- Please select a country.
+ <span role="img" aria-label="Error">❌</span> Please select a country.
</div>
</div>
</form>
@@ -75,14 +77,15 @@ Supported by: Chrome 119 (Oct 2023), Edge 119 (Nov 2023), Firefox 88 (Apr 2021),
### CSS for Fallback
```css
-input:user-invalid,
-input.user-invalid-fallback {
+/* Applies to every field that can be invalid (input, select, textarea). :is() keeps the
+ rule working where :user-invalid isn't supported: in a plain selector list, one
+ unsupported selector drops the whole rule. */
+:is(:user-invalid, .user-invalid-fallback) {
border-color: #d93025;
background-color: #fce8e6;
}
-input:user-invalid + .error-msg,
-input.user-invalid-fallback + .error-msg {
+:is(:user-invalid, .user-invalid-fallback) + .error-msg {
display: block;
}
```
@@ -96,17 +99,26 @@ const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
- const isValid = input.checkValidity();
+ // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
+ const isValid = input.validity.valid;
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
- if (!isValid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+ input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
+ linkError(input, !isValid);
+ };
+
+ // List the error message (the id in data-error) in aria-describedby only while it's
+ // shown: text that aria-describedby references is announced even when it's hidden.
+ const linkError = (input, shown) => {
+ const errorId = input.dataset.error;
+ if (!errorId) return;
+ const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
+ else input.removeAttribute('aria-describedby');
};
const handleEvent = (event) => {
@@ -118,13 +130,22 @@ const UserInvalidFallback = (() => {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
- control.removeAttribute('aria-invalid');
+ if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
+ if (control.dataset?.error) linkError(control, false);
}
return;
}
if (!input.checkValidity) return;
+ // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
+ // field, including required fields the user never touched, so flag them all.
+ if (event.type === 'invalid') {
+ dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
+ updateState(input);
+ return;
+ }
+
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasInteracted = true;
@@ -145,9 +166,15 @@ const UserInvalidFallback = (() => {
const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
+ // Firefox and Safari expose an empty required field as invalid from page load.
+ root.querySelectorAll('input, select, textarea').forEach((el) => {
+ if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
+ });
+
root.addEventListener('blur', handleEvent, true); // Capture phase
root.addEventListener('input', handleEvent);
root.addEventListener('change', handleEvent);
+ root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
root.addEventListener('reset', handleEvent, true); // Capture resets
};
@@ -164,15 +191,120 @@ UserInvalidFallback.init(form);
1. **Mobile behavior**: On mobile devices, "blur" might happen differently depending on the OS picker. Testing on actual devices is recommended.
2. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
+* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
+* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
+* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.
+
```javascript
-// Sync aria-invalid with the CSS :user-invalid state
-const syncAria = (el) => {
- el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
+// List the field's error message (the id in data-error) in aria-describedby only while
+// it's shown: text that aria-describedby references is announced even when it's hidden.
+const linkError = (el, shown) => {
+ const errorId = el.dataset.error;
+ if (!errorId) return;
+ const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
+ else el.removeAttribute('aria-describedby');
+};
+
+// One polite live region for the page announces an error that appears when the user
+// leaves or changes a field. Run this once the form is in the page.
+const announcer = document.createElement('div');
+announcer.setAttribute('aria-live', 'polite');
+announcer.classList.add('visually-hidden');
+document.body.append(announcer);
+let announceTimer;
+let announcedField;
+
+// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
+const spokenText = (node) => {
+ const copy = node.cloneNode(true);
+ copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
+ copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
+ return copy.textContent.replace(/\s+/g, ' ').trim();
+};
+const announceError = (el) => {
+ const error = document.getElementById(el.dataset.error);
+ if (!error) return;
+ const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ announcedField = el;
+ // Wait until the screen reader has announced the field that receives focus next.
+ announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
};
-// Update on blur (to show error) and input (to clear it)
-document.addEventListener('blur', (e) => syncAria(e.target), true);
+// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
+// an aria-invalid="true" that this script didn't set (for example from a server check)
+// is left alone.
+const flagged = new WeakSet();
+// Fields whose current error has been announced, or read out by focus after a failed
+// submit. A field can become invalid while the user types, so this is tracked separately.
+const announced = new WeakSet();
+const syncAria = (el, announce = false) => {
+ if (!el.matches?.('input, select, textarea')) return;
+ const invalid = el.matches(':user-invalid');
+ if (invalid) {
+ if (announce && !announced.has(el)) {
+ announceError(el);
+ announced.add(el);
+ }
+ el.setAttribute('aria-invalid', 'true');
+ linkError(el, true);
+ flagged.add(el);
+ } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
+ el.setAttribute('aria-invalid', 'false');
+ linkError(el, false);
+ flagged.delete(el);
+ announced.delete(el);
+ // Clear a fixed field's announcement so it isn't found later when reading the page.
+ if (announcedField === el) {
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ }
+ }
+};
+
+// Start every field at aria-invalid="false".
+document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));
+
+// Update on blur (to show and announce an error) and input (to clear it)
+document.addEventListener('blur', (e) => syncAria(e.target, true), true);
document.addEventListener('input', (e) => {
if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});
+
+// Checkboxes, radio buttons and other controls that commit on 'change' can become
+// :user-invalid without losing focus, so update on change too.
+document.addEventListener('change', (e) => syncAria(e.target, true), true);
+
+// A failed submit fires 'invalid' on each failing field, including required fields the
+// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
+// first invalid field announces its error, so these aren't announced.
+document.addEventListener('invalid', (e) => {
+ announced.add(e.target);
+ syncAria(e.target);
+}, true);
+
+// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
+document.addEventListener('reset', (e) => {
+ setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
+}, true);
+```
+
+Hide the live region with the `.visually-hidden` utility:
+
+```css
+/* Hides content visually but keeps it in the accessibility tree */
+.visually-hidden:where(:not(:focus-within, :active)) {
+ position: absolute !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ width: 1px !important;
+ height: 1px !important;
+ margin: -1px !important;
+ padding: 0 !important;
+ border: 0 !important;
+ white-space: nowrap !important;
+}
```
diff --git a/skills/modern-web-guidance/guides/forms/validate-input-after-interaction.md b/skills/modern-web-guidance/guides/forms/validate-input-after-interaction.md
index e880ed2..29ed1c6 100644
--- a/skills/modern-web-guidance/guides/forms/validate-input-after-interaction.md
+++ b/skills/modern-web-guidance/guides/forms/validate-input-after-interaction.md
@@ -6,7 +6,7 @@ Displaying validation errors the moment a user focuses on a field and starts typ
## The Solution
-The `:user-invalid` pseudo-class allows you to defer the error state until the user has "committed" to a value (by blurring the field) or attempted to submit the form. This ensures validation feedback is provided only after the user has finished interacting with the field.
+The `:user-invalid` pseudo-class allows you to defer the error state until the user has "committed" to a value (by modifying and blurring the field) or attempted to submit the form. This ensures validation feedback is provided only after the user has finished interacting with the field.
### Implementation Strategy
@@ -14,6 +14,8 @@ The `:user-invalid` pseudo-class allows you to defer the error state until the u
2. **Visual Feedback**: DO use `:user-invalid` to apply error styling only after interaction.
3. **Positive Reinforcement**: DO optionally use `:user-valid` to give a green "success" indicator once the requirements are met.
4. **Graceful Recovery**: As soon as the user corrects the input to a valid format, `:user-invalid` stops matching, removing the error state immediately.
+5. **Error Text**: DO show visible error text with the error styling, so the error isn't shown by color alone. DO start each message with an error icon that has a text alternative such as "Error" (the safest choice), or word every message as an error, for example "Please enter a valid email address.", and use the same approach for every error in the form. DO say how to fix the error when you know how, for example "Enter an email address in the format [email protected]."
+6. **Error Link**: DO list the error message in the field's `aria-describedby`, after any hint, only while the field is invalid, so screen readers read it with the field. A reference in the markup would read the hidden message from page load. The script in "Consistent ARIA Experience" does this for each field whose `data-error` attribute is set to its error message's `id`.
## Implementation Guide
@@ -28,6 +30,7 @@ MANDATORY: Rely on standard HTML5 attributes for email fields. The error message
<!-- MANDATORY: Place format hints above the input so autocomplete popovers don't cover them during editing -->
<span id="email-hint" class="hint">Format: [email protected]</span>
<!-- DO: Use standard HTML validation attributes like type="email" and required -->
+ <!-- Set data-error to the error message's id. The aria-invalid script lists that id in aria-describedby while the field is invalid. -->
<input
type="email"
id="email"
@@ -35,10 +38,10 @@ MANDATORY: Rely on standard HTML5 attributes for email fields. The error message
required
autocomplete="email"
aria-describedby="email-hint"
- aria-errormessage="email-error"
+ data-error="email-error"
>
<div id="email-error" class="error-msg">
- <span aria-hidden="true">❌</span> Please enter a valid email address.
+ <span role="img" aria-label="Error">❌</span> Enter an email address in the format [email protected].
</div>
</div>
</form>
@@ -91,12 +94,14 @@ MANDATORY: Define the complexity rule using a Regex Lookahead pattern in the `pa
<ul id="password-rules" class="rules-list">
<li>At least 8 characters</li>
<li>One uppercase letter</li>
+ <li>One lowercase letter</li>
<li>One number</li>
<li>One special character</li>
</ul>
<!-- DO: Use pattern and minlength for complex password validation
DO: Match all constraints with lookaheads via pattern attribute
-->
+ <!-- Set data-error to the error message's id. The aria-invalid script lists that id in aria-describedby while the field is invalid. -->
<input
type="password"
id="password"
@@ -105,7 +110,13 @@ MANDATORY: Define the complexity rule using a Regex Lookahead pattern in the `pa
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}"
minlength="8"
aria-describedby="password-rules"
+ data-error="password-error"
>
+ <!-- MANDATORY: Give the password its own error text. Turning the rules list red
+ doesn't say what is wrong, and screen readers don't convey the color change. -->
+ <div id="password-error" class="error-msg">
+ <span role="img" aria-label="Error">❌</span> Password doesn't meet all the requirements listed above.
+ </div>
</div>
</form>
```
@@ -123,6 +134,11 @@ input:user-invalid {
background-color: #fce8e6;
}
+/* DO: Reveal the error message using the adjacent sibling selector */
+input:user-invalid + .error-msg {
+ display: block;
+}
+
/* DO: Highlight rules list when error is shown using the modern :has() selector */
.field:has(input:user-invalid) .rules-list {
color: #d93025;
@@ -134,9 +150,11 @@ input:user-valid {
border-color: #188038;
}
-/* DO: Hide rules once satisfied */
+/* DO: Hide rules once satisfied. visibility keeps their space: collapsing the list on
+ blur would move the submit button between mousedown and mouseup, and the click
+ would be lost. */
.field:has(input:user-valid) .rules-list {
- display: none;
+ visibility: hidden;
}
```
@@ -150,14 +168,15 @@ Supported by: Chrome 119 (Oct 2023), Edge 119 (Nov 2023), Firefox 88 (Apr 2021),
### CSS for Fallback
```css
-input:user-invalid,
-input.user-invalid-fallback {
+/* Applies to every field that can be invalid (input, select, textarea). :is() keeps the
+ rule working where :user-invalid isn't supported: in a plain selector list, one
+ unsupported selector drops the whole rule. */
+:is(:user-invalid, .user-invalid-fallback) {
border-color: #d93025;
background-color: #fce8e6;
}
-input:user-invalid + .error-msg,
-input.user-invalid-fallback + .error-msg {
+:is(:user-invalid, .user-invalid-fallback) + .error-msg {
display: block;
}
```
@@ -171,17 +190,26 @@ const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
- const isValid = input.checkValidity();
+ // validity.valid gives the current state without firing an 'invalid' event, as checkValidity() does.
+ const isValid = input.validity.valid;
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
- if (!isValid) {
- input.setAttribute('aria-invalid', 'true');
- } else {
- input.removeAttribute('aria-invalid');
- }
+ input.setAttribute('aria-invalid', isValid ? 'false' : 'true');
+ linkError(input, !isValid);
+ };
+
+ // List the error message (the id in data-error) in aria-describedby only while it's
+ // shown: text that aria-describedby references is announced even when it's hidden.
+ const linkError = (input, shown) => {
+ const errorId = input.dataset.error;
+ if (!errorId) return;
+ const ids = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) input.setAttribute('aria-describedby', ids.join(' '));
+ else input.removeAttribute('aria-describedby');
};
const handleEvent = (event) => {
@@ -193,13 +221,22 @@ const UserInvalidFallback = (() => {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
- control.removeAttribute('aria-invalid');
+ if (control.matches('input, select, textarea')) control.setAttribute('aria-invalid', 'false');
+ if (control.dataset?.error) linkError(control, false);
}
return;
}
if (!input.checkValidity) return;
+ // A submit attempt counts as interaction: the browser fires 'invalid' on each failing
+ // field, including required fields the user never touched, so flag them all.
+ if (event.type === 'invalid') {
+ dirtyState.set(input, { hasInteracted: true, hasBlurred: true });
+ updateState(input);
+ return;
+ }
+
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasInteracted = true;
@@ -220,9 +257,15 @@ const UserInvalidFallback = (() => {
const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
+ // Firefox and Safari expose an empty required field as invalid from page load.
+ root.querySelectorAll('input, select, textarea').forEach((el) => {
+ if (!el.hasAttribute('aria-invalid')) el.setAttribute('aria-invalid', 'false');
+ });
+
root.addEventListener('blur', handleEvent, true); // Capture phase
root.addEventListener('input', handleEvent);
root.addEventListener('change', handleEvent);
+ root.addEventListener('invalid', handleEvent, true); // invalid doesn't bubble
root.addEventListener('reset', handleEvent, true); // Capture resets
};
@@ -244,15 +287,120 @@ UserInvalidFallback.init(form);
4. **Focus Management**: MANDATORY: If a user submits the form with an invalid field, the browser will automatically focus the first invalid field. Your `:user-invalid` styles will apply immediately because a submission attempt counts as an interaction.
5. **Consistent ARIA Experience**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:
+* Set `aria-invalid="false"` until `:user-invalid` matches, rather than leaving it unset. Firefox and Safari expose an empty `required` field as invalid from page load, and Chromium doesn't expose an empty `required` field as invalid after interaction unless `aria-invalid="true"` is set.
+* Link each field to its error message by setting the field's `data-error` attribute to the error message's `id` (`data-error="email-error"` for `<div id="email-error">`), and let the script list that `id` in `aria-describedby` only while the field is invalid. Don't reference the error from `aria-describedby` in the markup: the error element is always in the page, and text that `aria-describedby` references is announced even when it's hidden.
+* Announce an error that appears when the user leaves or changes a field through one polite live region for the page, a moment later so it doesn't talk over the next field. Don't make each error message a live region: a live region that is shown, rather than changed, isn't announced reliably. After a failed submit, move focus to the first invalid field so that its error is announced instead.
+
```javascript
-// Sync aria-invalid with the CSS :user-invalid state
-const syncAria = (el) => {
- el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
+// List the field's error message (the id in data-error) in aria-describedby only while
+// it's shown: text that aria-describedby references is announced even when it's hidden.
+const linkError = (el, shown) => {
+ const errorId = el.dataset.error;
+ if (!errorId) return;
+ const ids = (el.getAttribute('aria-describedby') || '').split(/\s+/).filter((id) => id && id !== errorId);
+ if (shown) ids.push(errorId);
+ if (ids.length) el.setAttribute('aria-describedby', ids.join(' '));
+ else el.removeAttribute('aria-describedby');
};
-// Update on blur (to show error) and input (to clear it)
-document.addEventListener('blur', (e) => syncAria(e.target), true);
+// One polite live region for the page announces an error that appears when the user
+// leaves or changes a field. Run this once the form is in the page.
+const announcer = document.createElement('div');
+announcer.setAttribute('aria-live', 'polite');
+announcer.classList.add('visually-hidden');
+document.body.append(announcer);
+let announceTimer;
+let announcedField;
+
+// Text as a screen reader reads it: icons' text alternatives in, aria-hidden text out.
+const spokenText = (node) => {
+ const copy = node.cloneNode(true);
+ copy.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove());
+ copy.querySelectorAll('[role="img"][aria-label]').forEach((n) => n.replaceWith(`${n.getAttribute('aria-label')}: `));
+ return copy.textContent.replace(/\s+/g, ' ').trim();
+};
+const announceError = (el) => {
+ const error = document.getElementById(el.dataset.error);
+ if (!error) return;
+ const label = el.labels?.[0] ? `${spokenText(el.labels[0])}: ` : '';
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ announcedField = el;
+ // Wait until the screen reader has announced the field that receives focus next.
+ announceTimer = setTimeout(() => { announcer.textContent = label + spokenText(error); }, 500);
+};
+
+// Sync aria-invalid with the CSS :user-invalid state. Only form fields are synced, and
+// an aria-invalid="true" that this script didn't set (for example from a server check)
+// is left alone.
+const flagged = new WeakSet();
+// Fields whose current error has been announced, or read out by focus after a failed
+// submit. A field can become invalid while the user types, so this is tracked separately.
+const announced = new WeakSet();
+const syncAria = (el, announce = false) => {
+ if (!el.matches?.('input, select, textarea')) return;
+ const invalid = el.matches(':user-invalid');
+ if (invalid) {
+ if (announce && !announced.has(el)) {
+ announceError(el);
+ announced.add(el);
+ }
+ el.setAttribute('aria-invalid', 'true');
+ linkError(el, true);
+ flagged.add(el);
+ } else if (flagged.has(el) || el.getAttribute('aria-invalid') !== 'true') {
+ el.setAttribute('aria-invalid', 'false');
+ linkError(el, false);
+ flagged.delete(el);
+ announced.delete(el);
+ // Clear a fixed field's announcement so it isn't found later when reading the page.
+ if (announcedField === el) {
+ clearTimeout(announceTimer);
+ announcer.textContent = '';
+ }
+ }
+};
+
+// Start every field at aria-invalid="false".
+document.querySelectorAll('input, select, textarea').forEach((el) => syncAria(el));
+
+// Update on blur (to show and announce an error) and input (to clear it)
+document.addEventListener('blur', (e) => syncAria(e.target, true), true);
document.addEventListener('input', (e) => {
if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});
+
+// Checkboxes, radio buttons and other controls that commit on 'change' can become
+// :user-invalid without losing focus, so update on change too.
+document.addEventListener('change', (e) => syncAria(e.target, true), true);
+
+// A failed submit fires 'invalid' on each failing field, including required fields the
+// user never touched, so update those too. 'invalid' doesn't bubble. Focus moving to the
+// first invalid field announces its error, so these aren't announced.
+document.addEventListener('invalid', (e) => {
+ announced.add(e.target);
+ syncAria(e.target);
+}, true);
+
+// Reset clears :user-invalid after the 'reset' event, so update each field afterwards.
+document.addEventListener('reset', (e) => {
+ setTimeout(() => [...e.target.elements].forEach((el) => syncAria(el)));
+}, true);
+```
+
+Hide the live region with the `.visually-hidden` utility:
+
+```css
+/* Hides content visually but keeps it in the accessibility tree */
+.visually-hidden:where(:not(:focus-within, :active)) {
+ position: absolute !important;
+ clip-path: inset(50%) !important;
+ overflow: hidden !important;
+ width: 1px !important;
+ height: 1px !important;
+ margin: -1px !important;
+ padding: 0 !important;
+ border: 0 !important;
+ white-space: nowrap !important;
+}
```
diff --git a/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md b/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md
index ae0ab6c..4f3d261 100644
--- a/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md
+++ b/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md
@@ -65,6 +65,16 @@ Key points:
- Implement `formResetCallback`, `formDisabledCallback`, and `formStateRestoreCallback` so the element behaves like a native control on reset, `fieldset[disabled]`, and back/forward autofill restore. In `formDisabledCallback(disabled)`, disable internal controls (or remove them from the tab order and ignore input) rather than setting `disabled` on the host — setting the host attribute inside the callback prevents re-enabling when an ancestor `<fieldset>` is re-enabled, and the host already matches `:disabled` automatically.
- Follow platform conventions for dispatched events and prefer the built-in `input` and `change` events over custom ones. `input` fires when the value changes as a direct result of user action (typing, dragging a slider); `change` fires once per stream of changes, when the user commits (releasing the slider, blurring the field). Construct them with `InputEvent` and `Event` respectively.
+## Accessibility considerations
+
+When creating custom elements, if the custom element directly handles interaction, or acts as a group for individual controls, ensure that the custom element has a role, and conveys state information (in the case of handling interaction directly). This can be done by using the appropriate properties of ElementInternals.
+
+```js
+this.#internals.role = 'group';
+```
+
+Unless the custom element contains its own visible label (which may be applicable for single checkbox-like custom elements), then don't apply an accessible name directly using the ElementInternals. This is because this would likely override any accessible name set when using the custom element, such as by labelling the element using a HTML label's `for` attribute.
+
## Fallback strategies
Baseline status for Form-associated custom elements: Widely available. It's been Baseline since 2023-03-27.
diff --git a/skills/modern-web-guidance/guides/html/html.md b/skills/modern-web-guidance/guides/html/html.md
index c13fce5..75b22a0 100644
--- a/skills/modern-web-guidance/guides/html/html.md
+++ b/skills/modern-web-guidance/guides/html/html.md
@@ -16,25 +16,27 @@
### Guidelines
-- **DO** use the standard HTML5 doctype `<!DOCTYPE html>` to prevent quirky rendering modes.
-- **DO** set the `lang` attribute on the `<html>` element for screen reader pronunciation and translation tools.
+- **DO** use the standard HTML5 doctype `<!DOCTYPE html>` to prevent quirky rendering modes.
+- **DO** set the `lang` attribute on the `<html>` element set to the primary document language and on any element that uses a language that differs from the primary language, for screen reader pronunciation and translation tools, and any locale-sensitive features (e.g. CSS `hyphens`).
- **DO** use the `<meta name="viewport">` element with the `content` attribute set to `"width=device-width, initial-scale=1.0"` to ensure page responsiveness.
- **DO** use a single `<h1>` per page/view representing the main topic. Exceptions can be made for modal dialogs, which can also use a single `<h1>`.
- **DO** maintain a sequential, non-skipping heading hierarchy (`<h2>` to `<h3>`, but not `<h2>` to `<h4>`).
- **DO** use semantic landmarks (`<header>`, `<nav>`, `<main>`, `<aside>`, `<footer>`) to create regional navigation for assistive technologies.
- **DO** use `<search>` to enclose search and filtering mechanisms (eliminates the need for `role="search"`).
- **DO** use `<button>` for triggered actions (JS, Modals, Forms) and `<a>` strictly for URL navigation. Set `type="button"` for non-submit buttons in forms to prevent unintended submission.
-- **DO** use `<ul>`, `<ol>`, and `<dl>` elements for list content.
-- **DO** ensure that all interactive elements like links and buttons have accessible names.
-- **DO** hide purely decorative SVG images from assistive technology using `aria-hidden="true"`. If using a decorative `<img>`, always include an empty `alt` attribute (e.g. `alt=""`).
-- **DO** ensure that informative SVGs like logos, data visualizations, or icon buttons have a proper accessible name.
+- **DO** use `<ul>`, `<ol>`, and `<dl>` elements for list content.
+- **DO** ensure that all interactive elements like links and buttons have accessible names.
+- Ensure that all interactive elements have a role that matches the interaction that they facilitate, whether that is their implicit role, or via the `role` attribute. Controls that trigger an interaction on the same page/in the same view should have a role of `button`, controls that redirect people should have a role of `link`.
+- **DO** hide purely decorative SVG images from assistive technology using `aria-hidden="true"`. If using a decorative `<img>`, always include an empty `alt` attribute (e.g. `alt=""`).
+- **DO** ensure that informative SVGs like logos, data visualizations, or icon buttons have a proper accessible name, and for more complex visuals, an accompanying text alternative, providing the same information as that conveyed visually.
- **DON'T** use generic `<div>` or `<span>` when semantic elements exist, for instance for interactive elements, headings, or independently reusable self-contained content.
- **DON'T** use boolean attributes with redundant values (e.g., use `disabled`, not `disabled="disabled"`).
- **DON'T** use generic elements with added ARIA roles or states when native elements with built-in semantics and behavior exist.
- **DON'T** change the native semantics of elements with ARIA unless it is a critical requirement.
-- **DON'T** use `role="presentation"` or `aria-hidden="true"` on focusable elements or their parents and ancestors.
+- **DON'T** use `role="presentation"` or `aria-hidden="true"` on focusable elements or their parents and ancestors.
- **DON'T** disable page zooming capabilities.
+- **DON'T** use more than one `banner`, `main`, or `contentinfo` landmark per page
### Code Example
@@ -68,6 +70,9 @@
<h2>First post</h2>
</article>
</main>
+ <footer>
+ Platform - Policies and legal information
+ </footer>
</body>
</html>
```
@@ -83,6 +88,7 @@
- **DO** use the `<code>` element for short fragments of computer code (e.g., variable names, file paths, or inline snippets).
- **DO** wrap `<code>` inside a `<pre>` element when displaying blocks of code to preserve whitespace and line breaks.
- **DO** ensure that code blocks are accessible by adding `tabindex="0"` to the `<pre>` element if it becomes scrollable, allowing keyboard users to reach the content.
+- **DO** ensure that scrollable code blocks are accessible by adding `role="region"` to the `<pre>`, along with an accessible name using either `aria-labelledby` (referencing the ID of the element that titles the block) or `aria-label`.
- **DON'T** use `<blockquote>` for purely visual indentation of non-quoted text.
- **DON'T** use `<figure>` for every single image; use it only when a caption is required or when the content is a distinct, referenced unit.
@@ -115,8 +121,8 @@
<!-- Code block with accessibility and language hint -->
<figure>
- <figcaption>Example configuration:</figcaption>
- <pre tabindex="0"><code class="language-json">
+ <figcaption id="code-block-caption">Example configuration:</figcaption>
+ <pre role="region" aria-labelledby="code-block-caption" tabindex="0"><code class="language-json">
{
"name": "gemini-cli",
"version": "1.0.0",
@@ -203,6 +209,7 @@
See `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`) for more info on fallback strategies for using the Popover API in a cross-browser way.
- **DO** use `<dialog>` for modal overlays (requires JS `.showModal()`) to automatically trap focus, dim backgrounds, and support dismissing via `Esc`. Use the `closedby="any"` attribute to enable native "light-dismiss" (closing on backdrop click) without custom JavaScript.
+- **DO** provide a visible control for closing modal overlays, so that people using voice control software can easily determine how to dismiss the modal dialog.
- **DO** utilize the Popover API (`popover` attribute) for non-modal UI (menus, tooltips) that do not require focus traps.
- **DO** use `::backdrop` to style modal backgrounds.
- **DO** use `<form method="dialog">` to dismiss dialogs without manual JS handlers. Combined button `formmethod="dialog"` yields the button's value to the dialog `.returnValue`.
@@ -258,29 +265,32 @@ See `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest
### Guidelines
-- **DO** use `<details>` and `<summary>` for native accordions or revealable content without JS.
+- **DO** use `<details>` and `<summary>` for a native disclosure pattern without JS.
+- **DO** use `<details>` and `<summary>` for native accordion patterns without JS. For exclusive accordions, use the `name` attribute on the `<details>` elements. Wrap the entire accordion in a `<section>` element with an accessible name provided using either `aria-labelledby` (referencing the `id` attribute of the element that names this accordion) or `aria-label`
- **DO** place `<summary>` as the *first* child of `<details>`.
- If headings must be used within a `<summary>`, consider if the heading is essential for understanding or navigating the document structure. If it is, use a more robust disclosure approach that allows wrapping the disclosure trigger with the heading (e.g. `<h2><button type="button" aria-expanded="false" aria-controls="significant-section-content">Significant section</button></h2>`). This ensures the heading semantics aren’t lost, and the button and its state are announced.
- **DO** use `details[open]` attribute for styling expanded states.
- **DO** use `details::details-content` for styling the contents of the `<details>` element.
-- **DO** use the `name` attribute on multiple `<details>` elements to create exclusive accordions (opening one closes others).
-- **DON'T** nest other interactive elements (links, buttons) directly inside `<summary>` text as it acts as a button and breaks focus.
+- **DON'T** nest other interactive elements (links, buttons) directly inside `<summary>` text as it may break expected focus behavior and screen reader announcements.
- **DON'T** hide visible triangles via `list-style: none` without providing explicit directional cues (via `::before`/`::after` pseudo-elements).
-- **DON'T** use the `title` attribute to create tooltip effects.
+- **DON'T** use the `title` attribute to create tooltip effects, as these cannot be accessed using a keyboard. Instead, use accessible tooltip patterns that can be triggered using a keyboard, and are consistently announced by screen readers.
+- **DON'T** provide text alternatives for custom state indicator icons (implemented using `<img>` or `<svg>` elements), as state should be communicated by the `<summary>` element, and a text alternative would duplicate this information
### Code Example
```html
<!-- Exclusive Accordion Set -->
-<details name="faq">
- <summary>Item 1</summary>
- <p>Contents...</p>
-</details>
-<details name="faq">
- <summary>Item 2</summary>
- <p>Contents...</p>
-</details>
+<section aria-label="Frequently asked questions">
+ <details name="faq">
+ <summary>Item 1</summary>
+ <p>Contents...</p>
+ </details>
+ <details name="faq">
+ <summary>Item 2</summary>
+ <p>Contents...</p>
+ </details>
+</section>
```
## 6. Focus Boundaries and Visibility
@@ -289,7 +299,10 @@ See `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest
- **DO** use the global `inert` attribute for entire hidden sections (off-screen menus, background while custom modal is open) to remove them from tab flows and accessibility trees.
- **DO** pair `[inert]` with CSS (`opacity: 0.5`) to visually signify inactivity.
-- **DO** rely on natural DOM order for sequential navigation.
+- **DO** rely on natural DOM order for sequential navigation.
+- **DO** ensure that focusable elements aren't obscured by anything when they receive focus (for example, focus should move to modal dialogs and be constrained in them, rather than being able to access obscured content behind the modal).
+- **DO** maintain focus—moving it to a logical adjacent element or returning it to the trigger control—when the currently focused element is hidden or removed.
+- **DO** move focus to the start of newly injected content when it is added in direct response to a user action that shifts the workflow into that content (e.g., opening a dialog or navigating to a new view), rather than for background or live-region updates.
- **DON'T** use positive `tabindex` values (e.g., `1`, `2`). Use `0` to add element to tab flow, or `-1` for JS program focus.
- **DON'T** alter focus flow using CSS properties (`flex-flow: row-reverse`, `order`) without aligning the DOM structure.
@@ -322,11 +335,13 @@ See `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest
See `forms` (via `npx -y modern-web-guidance@latest retrieve "forms"`) for more details on creating modern web forms.
- **DO** utilize the `form="form-id"` attribute to decouple inputs from the physical `<form>` tree.
-- **DO** use `<datalist>` coupled with `<input list="id">` for lightweight auto-suggestions (note: visually unstylable and has screen-reader quirks).
+- **DO** use `<datalist>` coupled with `<input list="id">` for lightweight auto-suggestions (note: visually unstylable and has screen-reader quirks).
+- **DO** use the `autocomplete` attribute and appropriate value on input fields that request personal information (for combined name fields use `autocomplete="name"`, for a given name use `autocomplete="given-name"`, for a family name use `autocomplete="family-name"`.)
+- **DO** distinguish `autocomplete="current-password"` (sign-in) from `autocomplete="new-password"` (registration / password change) so password managers offer the right action.
+- **DO** match `autocomplete` tokens with appropriate `inputmode` and `type` (`type="email"` + `inputmode="email"` + `autocomplete="email"`). They control different things — keyboard, validation, and autofill respectively — and reinforce each other.
+
- **DON'T** use `autocomplete="off"` on credential, address, payment, or contact fields. Browsers and password managers ignore it there by design. Use a specific token instead (`autocomplete="email"`, `"street-address"`, `"cc-number"`, etc.).
- **DON'T** use `autocomplete="off"` unless handling highly sensitive tracking tokens (violates standard password manager overrides). Use standard inputs `type="email"`, `type="tel"`.
-- **DO** distinguish `autocomplete="current-password"` (sign-in) from `autocomplete="new-password"` (registration / password change) so password managers offer the right action.
-- **DO** match `autocomplete` tokens with appropriate `inputmode` and `type` (`type="email"` + `inputmode="email"` + `autocomplete="email"`). They control different things — keyboard, validation, and autofill respectively — and reinforce each other.
### Code Example
@@ -355,6 +370,7 @@ See `forms` (via `npx -y modern-web-guidance@latest retrieve "forms"`) for more
- **DON'T** rely on JS for basic video controls if native `controls` attribute is sufficient.
- **DON'T** apply `role="none"` or `aria-hidden="true"` to focusable elements (such as embedded interactive `<iframe>` components). Hiding elements from the assistive technology tree while leaving them accessible to sequential keyboard navigation violates core accessibility heuristics. The background video exception holds solely because omitting the `controls` attribute renders the `<video>` element fully non-focusable.
+- **DON'T** automatically play audio when a page is opened, unless there is an accessible stop or pause control, or a way to change the volume of the audio, independent from the operating system's volume level, as to adhere to WCAG 1.4.2 Audio Control, Level A.
### Code Example
@@ -374,10 +390,13 @@ See `forms` (via `npx -y modern-web-guidance@latest retrieve "forms"`) for more
## 9. Dynamic Styles and Interactivity
### Guidelines
+
- **DO** use the `style` attribute to pass state to CSS via **Custom Properties**. This keeps visual logic in your stylesheet while JavaScript provides the raw data.
+- **DO** ensure that information is available for people using screen readers, using text alternatives, appropriate accessible names, roles, and programmatic state information
- **DON'T** use inline styles for static design (colors, padding, margins) that belong in a stylesheet.
- **DON'T** use inline event handlers (e.g., `onclick`). Trigger actions using `addEventListener()`.
+- **DON'T** convey state, interaction, or information using color alone.
### Code Example
diff --git a/skills/modern-web-guidance/guides/html/web-components.md b/skills/modern-web-guidance/guides/html/web-components.md
index 3931909..0f3b15c 100644
--- a/skills/modern-web-guidance/guides/html/web-components.md
+++ b/skills/modern-web-guidance/guides/html/web-components.md
@@ -33,7 +33,7 @@ These hold across every guide below:
- **MANDATORY**: call `super()` first in the constructor, before touching `this`; calling it after any statement that reads or writes `this` throws.
- **MANDATORY**: use semantic elements (`<button>`, `<nav>`, `<ul>`) inside shadow templates. Most accessibility failures in shadow trees come from non-semantic markup; a slot does not change the role of what it projects.
- **MANDATORY**: ARIA `id` references (`aria-labelledby`, `aria-describedby`, `aria-controls`) cannot cross a shadow boundary; the referencing element and the `id` it points to must live in the same tree.
-- Prefer `attachShadow({ mode: 'open' })` so dev tools, page scripts, and server hydration can reach `element.shadowRoot`. Use `'closed'` only when you must hide internal structure from page scripts.
+- **MANDATORY**: attach shadow roots with `attachShadow({ mode: 'open' })` (or `shadowrootmode="open"` for Declarative Shadow DOM); `mode: 'closed'` hides `element.shadowRoot` from page scripts, test harnesses, and automated accessibility checkers that walk shadow trees.
- Avoid *customized built-in elements* (`extends HTMLButtonElement` with `is="…"`); Safari has permanently declined to ship them.
## Use-case guide matrix
diff --git a/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md b/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md
index 23c216e..fd307b9 100644
--- a/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md
+++ b/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md
@@ -1,6 +1,6 @@
# Break Up Long Tasks
-Heavy computations or long loops can block the main thread, causing the page to become unresponsive. To prevent this, you should yield control back to the browser periodically. The `scheduler.yield()` API allows you to pause a long task and let the browser handle user input or rendering before continuing.
+Heavy computations or long loops can block the main thread, delaying event handlers and causing poor Interaction to Next Paint (INP) responsiveness. To prevent this, you should yield control back to the browser periodically. The `scheduler.yield()` API allows you to pause a long task and let the browser handle user input or rendering before continuing.
### Breaking up long tasks
diff --git a/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md b/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
index 4d9ecc5..0322c7c 100644
--- a/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
+++ b/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
@@ -6,19 +6,42 @@ Out-of-Order (OOO) HTML Streaming (also known as Declarative Partial Updates) is
The feature consists of two primary mechanisms:
-1. **Declarative Patching (HTML-based)**: Uses new processing instructions (`<?marker>`, `<?start>`, `<?end>`) and `<template for>` to swap content in the DOM as it streams in from the server.
-2. **Imperative setting and streaming (JS-based)**: A suite of new methods (e.g., `streamHTML()`, `setHTMLUnsafe()`) that allow setting of HTML or piping readable streams directly into DOM elements with native performance and optional script execution.
+1. **Declarative Patching (HTML-based)**: Uses new processing instructions (`<?marker>`, `<?start>`, `<?end>`) and `<template for>` to swap content in the DOM as it streams in from the server.
+2. **Imperative setting and streaming (JS-based)**: A suite of new methods (e.g., `streamHTML()`, `setHTMLUnsafe()`) that allow setting of HTML or piping readable streams directly into DOM elements with native performance and optional script execution.
## Best Practices
-* **Prioritize Above-the-Fold Content**: Stream critical UI (header, hero, primary navigation, primary content) first. Use placeholders for "expensive" or lower priority components like comments, ads, or related content.
-* **Implement Native Loading States**: Use the `<?start>` and `<?end>` markers to wrap fallback content. The browser automatically replaces everything between these markers when the corresponding `<template for>` arrives.
-* **Minimize Cumulative Layout Shift (CLS)**: Always provide stable dimensions for placeholders. If the final content size is unknown, use skeleton screens or CSS `aspect-ratio` to reserve space and prevent jarring shifts.
-* **Accessibility & Focus Management**: Be mindful that out-of-order updates can confuse screen reader users. Use `aria-live` regions for critical updates and ensure that focus isn't lost if a placeholder containing the active element is replaced.
+* **Prioritize Above-the-Fold Content**: Stream critical UI (header, hero, primary navigation, primary content) first. Use placeholders for "expensive" or lower priority components like comments, ads, or related content.
+* **Implement Native Loading States**: Use the `<?start>` and `<?end>` markers to wrap fallback content. The browser automatically replaces everything between these markers when the corresponding `<template for>` arrives.
+* **Minimize Cumulative Layout Shift (CLS)**: Always provide stable dimensions for placeholders. If the final content size is unknown, use skeleton screens or CSS `aspect-ratio` to reserve space and prevent jarring shifts.
+
+## Accessibility Considerations
+
+Be mindful that out-of-order updates can confuse screen reader users, people with cognitive impairments, and people who do not use a mouse or touch to interact with page content. In particular, make sure that focus is not lost if a placeholder containing the active element is replaced.
+
+Additionally, and particularly when contents take a subjectively long time to stream, it may be necessary to provide text-based progress information, such as a "Loading..." notification, wrapped in a live region to prevent people from thinking that the page is "broken".
+
+However, while it is tempting to inform them about every change to page content while it is being streamed, too many notifications can be disruptive and irritating, even when implemented with the best intentions. In particular:
+
+* MANDATORY: Only apply the live region markup to the container for the text that indicates progress. Do not wrap the entire content in a live region, as this will cause screen readers to announce the full "patched" content when streaming is complete, which can overwhelm screen reader users.
+* MANDATORY: Do not use `role="alert"` for conveying progress information. Some screen readers such as NVDA will announce the term "Alert" before announcing the live region text, which can be irritating for screen reader users, particularly when the related content doesn't represent an alert.
+
+To decide on the best approach, be mindful of the type of content that is being streamed, and the types of components that are being populated by the streaming content.
+
+For example, consider the following use cases.
+
+1. **A dashboard-type user interface made up of several panels:** The content for each panel is opened in stages before the user can interact with the main content section as a whole, and - for some panels - it takes some time for some content to load, often up to a minute or more. Here, a live region-based notification is necessary. Apply the `aria-busy` attribute with a value of `true` to the container for the affected panels so that screen reader users are aware that the contents are not ready for interaction. This attribute should then be set to `false` when the streaming is complete.
+ * MANDATORY: Do not nest the live region-based notification inside panels with `aria-busy="true"`, as this will prevent screen readers announcing the live region until after all of the content has been loaded.
+ * MANDATORY: Focus must remain where it is while content is loading; it must not move to the content during the loading process or when loading is complete.
+2. **A single page application:** An app is made up of a single HTML document. Rather than open a new page when a link is activated, the existing page content is automatically replaced with new content via streaming. Unless there is a delay due to the streaming content taking time to render, a live region-based notification is unnecessary. However, focus should move to the start of the new content when streaming is complete.
+3. **A product page where content is streamed as the user scrolls the page:** When the page loads, the user is presented with a list of 10 products. As they scroll the page, additional products are added to the list via streaming. There is a short delay to allow the streaming content to load, during which time a "Loading additional products..." message is displayed and then replaced with the new content. Similarly to the first use case, this message should be wrapped in a live region, the `aria-busy` attribute should be applied to the container for the updating content (being reset to `aria-busy="false"` when the content is fully loaded), and focus should remain where it is and not move to the new content.
+4. **A mega menu with a submenu whose content is rendered via streaming:** Whether the submenu content is streamed out-of-order while still collapsed or streamed almost immediately when expanded, it can be interacted with in the same way as if it weren't streamed. Here, the impact on screen reader users is negligible, so there is no need for a live region or any additional focus management.
+5. **A profile widget that is added to the header after an API call is made to check the current status:** On initially loading the page, a "Login" link is displayed at the right-hand side of the header. If the user is already logged in, this is immediately replaced with a profile menu button. For such users, the change is barely noticeable. Like in the previous use case, there is no need to include a live region-based notification, nor should focus be moved to the new content.
## Implementation Details
### 1. Declarative HTML Markers
+
The browser looks for specific processing instructions to identify where content should be patched.
```html
@@ -30,7 +53,7 @@ The browser looks for specific processing instructions to identify where content
<!-- A replacement range with loading state -->
<main>
<?start name="main-content">
- <div class="skeleton">Loading content...</div>
+ <div class="skeleton" role="status">Loading main content...</div>
<?end>
</main>
@@ -86,12 +109,12 @@ The browser provides a suite of 24 methods (6 actions, each with 4 variations) t
#### Key Concepts
-* **Safe vs. Unsafe**:
- * **Safe** methods (e.g., `setHTML()`) use a built-in sanitizer by default to strip potentially dangerous content like `<script>` tags. You can pass a custom `Sanitizer` object in the options to apply in addition to the default sanitizer.
- * **Unsafe** methods (e.g., `setHTMLUnsafe()`) do not sanitize by default, but you can still pass a custom `Sanitizer`. To allow scripts to execute in the new content, you must explicitly pass `{ runScripts: true }` in the options. **IMPORTANT**: Only use unsafe methods with trusted content where safe methods would not work.
-* **Static vs. Streaming**:
- * **Static** methods take a string (or `TrustedHTML`) and apply it immediately.
- * **Streaming** methods return a `WritableStream`. This allows you to pipe content (e.g., from a `fetch` response) directly into the DOM, and the browser will render it incrementally as chunks arrive.
+* **Safe vs. Unsafe**:
+ * **Safe** methods (e.g., `setHTML()`) use a built-in sanitizer by default to strip potentially dangerous content like `<script>` tags. You can pass a custom `Sanitizer` object in the options to apply in addition to the default sanitizer.
+ * **Unsafe** methods (e.g., `setHTMLUnsafe()`) do not sanitize by default, but you can still pass a custom `Sanitizer`. To allow scripts to execute in the new content, you must explicitly pass `{ runScripts: true }` in the options. **IMPORTANT**: Only use unsafe methods with trusted content where safe methods would not work.
+* **Static vs. Streaming**:
+ * **Static** methods take a string (or `TrustedHTML`) and apply it immediately.
+ * **Streaming** methods return a `WritableStream`. This allows you to pipe content (e.g., from a `fetch` response) directly into the DOM, and the browser will render it incrementally as chunks arrive.
#### Example: Streaming a Fetch Response
@@ -114,16 +137,16 @@ await response
## Use Case Reference Matrix
-* **Island Architecture**: Hydrate independent interactive components on top of static HTML without a full framework runtime.
-* **Deferred "Expensive" Blocks**: Deliver the shell of a page immediately and stream database-heavy components as they become available.
-* **Single Page Application (SPA) Updates**: Stream large UI transitions in SPAs using `streamHTML()` instead of waiting for a full JSON payload and manual DOM construction.
+* **Island Architecture**: Hydrate independent interactive components on top of static HTML without a full framework runtime.
+* **Deferred "Expensive" Blocks**: Deliver the shell of a page immediately and stream database-heavy components as they become available.
+* **Single Page Application (SPA) Updates**: Stream large UI transitions in SPAs using `streamHTML()` instead of waiting for a full JSON payload and manual DOM construction.
## Anti-Patterns & Warnings (DO NOT DO THIS)
-* **Do not use OOO streaming for everything.** Over-fragmenting a page can increase the complexity of the stream and potentially delay content if the browser spends too much time patching small nodes.
-* **Do not ignore Trusted Types.** When using `*Unsafe` methods in environments with Trusted Types enforced, ensure you are passing a sanitized policy object if required.
-* **Do not assume script execution order.** Scripts inside a `<template for>` will execute as soon as they are patched into the document. Do not rely on them executing in a specific sequence relative to other deferred templates.
-* **Do not use without a polyfill strategy.** Ensure you have a fallback or use polyfills (`html-setters-polyfill` and `template-for-polyfill`) to support your required browsers until this feature becomes Baseline.
+* **Do not use OOO streaming for everything.** Over-fragmenting a page can increase the complexity of the stream and potentially delay content if the browser spends too much time patching small nodes.
+* **Do not ignore Trusted Types.** When using `*Unsafe` methods in environments with Trusted Types enforced, ensure you are passing a sanitized policy object if required.
+* **Do not assume script execution order.** Scripts inside a `<template for>` will execute as soon as they are patched into the document. Do not rely on them executing in a specific sequence relative to other deferred templates.
+* **Do not use without a polyfill strategy.** Ensure you have a fallback or use polyfills (`html-setters-polyfill` and `template-for-polyfill`) to support your required browsers until this feature becomes Baseline.
## Fallback strategies
diff --git a/skills/modern-web-guidance/guides/performance/performance.md b/skills/modern-web-guidance/guides/performance/performance.md
index 2a77100..c0122dc 100644
--- a/skills/modern-web-guidance/guides/performance/performance.md
+++ b/skills/modern-web-guidance/guides/performance/performance.md
@@ -78,7 +78,7 @@ LCP measures the time required to render the largest visible text or image block
<!-- Preloading a CSS-based LCP background -->
<link rel="preload" as="image" href="/images/bg-hero.webp" fetchpriority="high" type="image/webp">
-<!-- Demoting an above-the-fold non-LCP carousel image -->
+<!-- Demoting an offscreen non-LCP carousel image -->
<img src="/images/carousel-2.webp" fetchpriority="low" loading="lazy" alt="Slide 2">
```
diff --git a/skills/modern-web-guidance/guides/pwa/install-web-app.md b/skills/modern-web-guidance/guides/pwa/install-web-app.md
new file mode 100644
index 0000000..e99d14f
--- /dev/null
+++ b/skills/modern-web-guidance/guides/pwa/install-web-app.md
@@ -0,0 +1,400 @@
+# Installing web applications
+
+Use the Web Install API to give users an explicit, in-page way to install a web
+application. Installation is always completed through browser-controlled consent
+UI; websites cannot silently install an app.
+
+Use either the HTML `<install>` element or the JavaScript
+`navigator.install()` method.
+
+## Choose which install approach to use: HTML element or JavaScript method
+
+Decide to use either the HTML `<install>` element or the JavaScript
+`navigator.install()` method based on the following considerations.
+
+* `<install>` element:
+ * Pros:
+ * The browser provides the install control, ensuring a consistent and
+ trustworthy installation experience.
+ * Installing another app does not trigger a separate permission prompt
+ before the installation confirmation dialog.
+ * No JavaScript is required to trigger the installation.
+ * Cons:
+ * Visual customization of the button is restricted.
+ * The number of `<install>` elements on a page is capped by user-agent
+ anti-spam limits, making `navigator.install()` a better fit for large app
+ catalogs.
+
+* JavaScript `navigator.install()` method:
+
+ * Pros:
+ * The installation UI can be fully customized to match the look and feel of
+ the website.
+ * The number of installation UI elements is not limited by the browser.
+ * Cons:
+ * Requires JavaScript to trigger the installation.
+ * Installing another app triggers an initial `web-app-installation`
+ permission prompt before the installation confirmation dialog.
+
+## Prepare the web app
+
+The app being installed must have a web app manifest. Give the manifest a stable
+`id` so the browser can keep the app's identity separate from its launch URL.
+For installation of the current app, link the manifest from the document.
+
+```html
+<!-- The current document's manifest is used by the no-argument install APIs. -->
+<link rel="manifest" href="/manifest.webmanifest">
+```
+
+```json
+{
+ "id": "/",
+ "name": "Example application",
+ "short_name": "Example",
+ "start_url": "/",
+ "display": "standalone",
+ "icons": [
+ {
+ "src": "/icons/app-192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ },
+ {
+ "src": "/icons/app-512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ]
+}
+```
+
+Keep the manifest URL stable. For current-document installation, the manifest
+must explicitly declare an `id` that is same-origin with the document. When
+offering a different app by manifest URL, the manifest must be reachable over
+HTTPS without credentials or redirects (CORS headers are not required), return a
+JSON MIME `Content-Type` (such as `application/manifest+json`), and share the
+same origin as that app's `start_url`.
+
+## Use the HTML `<install>` element
+
+The `<install>` element renders a user-agent-controlled button. Prefer it when
+the browser's standard label and presentation are appropriate, because the
+browser-owned control gives users a trustworthy installation affordance.
+
+```html
+<!-- No attributes installs the current document's linked web app. -->
+<install></install>
+```
+
+To offer another web app (including a cross-origin app from an app catalog or
+suite launcher), provide its manifest URL. The target `manifest` URL and its
+`start_url` must share the same origin, and the manifest must be reachable
+without credentials or redirects and return a JSON MIME `Content-Type`:
+
+```html
+<install manifest="https://app.example/manifest.webmanifest"></install>
+```
+
+Prefer declaring an explicit, stable `id` in the target manifest. If the target
+manifest does not declare an `id`, you must supply its computed manifest ID in
+the `manifestid` attribute so the browser can verify the expected app identity:
+
+```html
+<install
+ manifest="https://app.example/manifest.webmanifest"
+ manifestid="https://app.example/"
+></install>
+```
+
+When a manifest omits `id`, the browser computes its fallback ID by resolving
+the manifest's `start_url` against the manifest URL (not the installing page)
+and stripping any URL fragment while keeping query parameters. For example, a
+manifest at `https://app.example/catalog/manifest.webmanifest` with no `id` and
+`"start_url": "../launch?source=catalog"` has a computed ID of
+`https://app.example/launch?source=catalog`. Supplying `manifestid` checks that
+computed identity; it does not override the manifest or keep the identity stable
+if `start_url` later changes.
+
+The `manifestid` attribute can either be absolute or relative. Relative values
+are resolved against the installing document's base URL, and the resulting URL
+must match the target manifest's processed ID.
+
+Do not imitate, overlay, or transform the browser-controlled element. Its
+presentation and activation restrictions protect users from deceptive
+installation prompts.
+
+### Handle installation success and errors
+
+Listen for the `installresult` event to handle installation success and errors
+and use the `event.result` property to determine the outcome:
+
+* `"success"`: the app was installed, or the user approved an action (such as
+ opening) for an already-installed app. Pages cannot distinguish between these
+ two cases.
+* `"aborted"`: the user canceled the installation or a browser condition
+ prevented the installation from completing.
+* `"invalid-data"`: the `manifest` or `manifestid` attribute values, manifest
+ response, or required manifest fields are invalid.
+
+```html
+<install></install>
+<p id="install-status" role="status"></p>
+
+<script type="module">
+ const installButton = document.querySelector("install");
+ const installStatus = document.querySelector("#install-status");
+
+ installButton.addEventListener("installresult", (event) => {
+ switch (event.result) {
+ case "success":
+ installStatus.textContent = "The app was installed or opened.";
+ break;
+ case "aborted":
+ installStatus.textContent =
+ "Installation was canceled or could not complete.";
+ break;
+ case "invalid-data":
+ installStatus.textContent =
+ "Installation could not start because the app data is invalid.";
+ break;
+ }
+ });
+</script>
+```
+
+## Use the JavaScript `navigator.install()` method
+
+Use `navigator.install()` in a secure context (HTTPS) when custom page UI is
+necessary. Keep the button hidden until a supported installation mechanism is
+available. Call `navigator.install()` directly from the click handler so the
+call retains the required transient user activation.
+
+```html
+<button id="install-app" type="button" hidden>Install app</button>
+<p id="install-status" role="status"></p>
+
+<script type="module">
+ const installButton = document.querySelector("#install-app");
+ const installStatus = document.querySelector("#install-status");
+ const supportsWebInstall =
+ typeof Navigator.prototype.install === "function";
+
+ if (supportsWebInstall) {
+ installButton.hidden = false;
+ }
+
+ installButton.addEventListener("click", async () => {
+ if (installButton.getAttribute("aria-disabled") === "true") {
+ return;
+ }
+ // Use aria-disabled instead of disabled so activating the button does not drop focus.
+ installButton.setAttribute("aria-disabled", "true");
+
+ try {
+ // MANDATORY: Call during the click handler; delayed calls lose user activation.
+ await navigator.install();
+ installStatus.textContent = "The app was installed or opened.";
+ installButton.hidden = true;
+ } catch (error) {
+ if (error.name === "AbortError") {
+ // Cancellation is an expected user choice; keep the button available to retry.
+ installStatus.textContent = "Installation was canceled or could not complete.";
+ } else {
+ installStatus.textContent = "Installation could not start.";
+ // Surface invalid manifests and unexpected platform failures to developers.
+ console.error(error);
+ }
+ } finally {
+ installButton.removeAttribute("aria-disabled");
+ }
+ });
+</script>
+```
+
+Calling `navigator.install()` with no arguments installs the current document's
+linked app and requires the manifest to declare an `id`.
+
+To offer another app (including a cross-origin app, provided the target
+`manifest` URL and its `start_url` share the same origin and the manifest is
+served over HTTPS with a JSON MIME `Content-Type`), pass its manifest URL:
+
+```js
+await navigator.install({
+ manifest: "https://app.example/manifest.webmanifest",
+});
+```
+
+Prefer declaring an explicit, stable `id` in the target manifest. If that
+manifest does not declare an `id`, also pass the target web app's computed
+manifest ID (`start_url` resolved against the manifest URL without fragments)
+so the browser can verify the expected identity:
+
+```js
+await navigator.install({
+ manifest: "https://app.example/manifest.webmanifest",
+ manifestId: "https://app.example/",
+});
+```
+
+The `manifestId` option can either be absolute or relative. Relative values are
+resolved against the installing document's base URL, and the resulting URL must
+match the target manifest's processed ID.
+
+### Handle installation success and errors
+
+The `navigator.install()` method returns a promise that resolves when the
+installation completes or when the user approves an action (such as opening) for
+an already-installed app. Pages cannot distinguish between these two cases.
+
+The promise rejects with the following errors if the installation fails or is
+canceled:
+
+* `AbortError`:
+ * The user aborted the installation.
+ * The permission was denied.
+ * The environment doesn't support installation.
+ * Multiple concurrent installation attempts.
+ * A page navigation occurred during the installation process.
+* `DataError`:
+ * Missing linked manifest, invalid or unreachable manifest URL, redirect, or non-JSON `Content-Type` header.
+ * Missing required manifest fields, or `start_url` is not same-origin with `manifest`.
+ * The manifest omits `id` and no `manifestId` was provided, or `manifestId` does not match the manifest's processed ID.
+* `NotAllowedError`:
+ * Missing transient user activation.
+* `TypeError`:
+ * An options argument omits `manifest`, or `manifest` or `manifestId` is empty or cannot be parsed as a URL.
+* `InvalidStateError`:
+ * The API was called from a detached document, subframe, or fenced frame.
+* `SecurityError`:
+ * The `web-app-installation` Permissions Policy is disabled or the document is sandboxed.
+
+## Fallback strategies
+
+The Web Install API is a progressive enhancement. Browsers without either modern
+entry point still provide their own installation UI when they support installing
+web apps.
+
+### Web app manifest fallback
+
+Browser support for Web app manifest: Limited availability.
+Supported by: Chrome 53 (Aug 2016), Edge 79 (Jan 2020), Safari 17 (Sep 2023), and Safari iOS 15.4 (Mar 2022).
+Unsupported in: Firefox.
+
+Browsers that do not use web app manifests can still present the application as
+a normal website. Treat installation and standalone display as enhancements; do
+not block access to core functionality when manifest-based installation is
+unavailable.
+
+### `<install>` fallback
+
+<install> is not natively supported by any major browser yet.
+
+The `<install>` element supports fallback child content for browsers that do not
+render the browser-controlled install button. Use fallback content to link to a
+maintained installation help page when the product provides one.
+
+```html
+<install>
+ <!-- Rendered only when the browser does not provide the install control. -->
+ <a href="/install-help">How to install this app</a>
+</install>
+```
+
+If browser-specific instructions would be inaccurate or difficult to maintain,
+leave the element empty. It then renders no non-functional replacement in an
+unsupported browser.
+
+For a custom install button, render it separately with `hidden` and reveal it
+only when `navigator.install()` is supported or a `beforeinstallprompt` event
+has been captured. Do not put an always-visible imitation of the
+browser-controlled install button inside the fallback content.
+
+### `navigator.install()` fallback
+
+navigator.install() is not natively supported by any major browser yet.
+
+When `navigator.install()` is unavailable, use the `beforeinstallprompt` event
+as a fallback for installing the current app. Unlike `navigator.install()`, this
+event cannot install a different app.
+
+### `beforeinstallprompt` fallback
+
+Browser support for beforeinstallprompt: Limited availability.
+Supported by: Chrome 76 (Jul 2019) and Edge 79 (Jan 2020).
+Unsupported in: Firefox and Safari.
+
+Capture the event, prevent its automatic prompt, and reveal the custom install
+button only after the browser confirms that prompting is possible. Use one click
+handler that selects `navigator.install()` when available and otherwise uses the
+captured event. The event is single-use, so discard it before awaiting the
+user's choice and hide the button unless a new `beforeinstallprompt` event fires.
+
+```js
+const installButton = document.querySelector("#install-app");
+const installStatus = document.querySelector("#install-status");
+const supportsWebInstall =
+ typeof Navigator.prototype.install === "function";
+let deferredInstallPrompt;
+
+if (supportsWebInstall) {
+ installButton.hidden = false;
+}
+
+window.addEventListener("beforeinstallprompt", (event) => {
+ event.preventDefault();
+ deferredInstallPrompt = event;
+
+ // Prefer navigator.install() when both mechanisms are available.
+ if (!supportsWebInstall) {
+ installButton.hidden = false;
+ }
+});
+
+installButton.addEventListener("click", async () => {
+ if (installButton.getAttribute("aria-disabled") === "true") {
+ return;
+ }
+ // Use aria-disabled instead of disabled so activating the button does not drop focus.
+ installButton.setAttribute("aria-disabled", "true");
+
+ try {
+ if (supportsWebInstall) {
+ // Call directly from this handler to preserve transient user activation.
+ await navigator.install();
+ installStatus.textContent = "The app was installed or opened.";
+ installButton.hidden = true;
+ } else if (deferredInstallPrompt) {
+ // Save and clear the single-use event before awaiting the user's choice.
+ const promptEvent = deferredInstallPrompt;
+ deferredInstallPrompt = undefined;
+ await promptEvent.prompt();
+ const { outcome } = await promptEvent.userChoice;
+
+ installStatus.textContent =
+ outcome === "accepted"
+ ? "The app was installed."
+ : "Installation canceled.";
+ if (!deferredInstallPrompt) {
+ installButton.hidden = true;
+ }
+ }
+ } catch (error) {
+ if (error.name === "AbortError") {
+ // Cancellation is an expected user choice; keep the button available to retry.
+ installStatus.textContent = "Installation was canceled or could not complete.";
+ } else {
+ installStatus.textContent = "Installation could not start.";
+ console.error(error);
+ }
+ } finally {
+ installButton.removeAttribute("aria-disabled");
+ }
+});
+```
+
+Do not show a non-functional install button in browsers that support neither
+mechanism. Hiding the button is graceful degradation: users can still use any
+installation affordance provided by their browser. Do not replace the hidden
+button with browser-specific step-by-step instructions unless the product has a
+tested, maintained onboarding flow for those browsers.
\ No newline at end of file
diff --git a/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md b/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md
index ca2b1d7..078ba7c 100644
--- a/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md
+++ b/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md
@@ -47,7 +47,7 @@ File location: `https://old-app.example.com/.well-known/web-app-origin-associati
```json
{
- "https://new-app.example.com": {
+ "https://new-app.example.com/demo.html": {
"allow_migration": true
}
}
@@ -55,16 +55,14 @@ File location: `https://old-app.example.com/.well-known/web-app-origin-associati
### 4. Proactively signal the migration (Optional)
-To trigger the migration immediately for existing users without waiting for them to visit the new site, update the **old** site's manifest with a `migrate_to` hint.
+To let the browser discover the migration from the old installation, without waiting for users to visit the new site, add a `migrate_to` member to the **old** site's `manifest.json`. Set its `id` to the new app's manifest ID:
```json
{
- "migrate_to": [
- {
- "id": "https://new-app.example.com/",
- "install_url": "https://new-app.example.com/demo.html"
- }
- ]
+ "migrate_to": {
+ "id": "https://new-app.example.com/demo.html",
+ "install_url": "https://new-app.example.com/demo.html"
+ }
}
```
diff --git a/skills/modern-web-guidance/guides/security/passkey-authentication.md b/skills/modern-web-guidance/guides/security/passkey-authentication.md
index f198027..8d96ba6 100644
--- a/skills/modern-web-guidance/guides/security/passkey-authentication.md
+++ b/skills/modern-web-guidance/guides/security/passkey-authentication.md
@@ -8,7 +8,7 @@ This guide details how to implement returning user authentication using discover
Create an endpoint that generates WebAuthn request parameters using a vetted library per standards.
-1. **Use the predefined RP ID**: Use the predefined proper RP ID as a constant string.
+1. **Use the predefined RP ID**: Use the predefined proper RP ID as a constant string and include it as `rpId` in the returned request options so the client can pass `publicKey.rpId` directly to Signal API calls.
2. **Generate challenge**: Generate a high-entropy, cryptographically secure random buffer, store it securely in the user's session, and encode it as Base64URL.
3. **Discoverable Credentials mapping**: Specify an empty array `[]` for `allowCredentials`. This requests discoverable credentials, meaning the user does not need to enter their username first; the passkey provider will present available accounts.
4. **User Verification level**: Set `userVerification: "preferred"` (or `"required"` if explicitly mandated by corporate compliance policies).
@@ -40,14 +40,20 @@ Securely verify the assertion returned by the client to authenticate the user:
### HTML Form Annotation
-Annotate your username and password inputs to natively leverage Conditional UI. Autocomplete tokens combine the webauthn spec parameters, and autofocus triggers the browser autofill popup immediately when the input is focused.
+Annotate your username and password inputs to natively leverage Conditional UI. Autocomplete tokens combine the webauthn spec parameters.
+
+Use the `autofocus` attribute on dedicated sign-in pages and sign-in dialogs so that the autofill options are immediately displayed. Do not use the `autofocus` attribute on pages or dialogs that are not dedicated sign-in forms. Do not use the `autofocus` attribute on sign-in forms that are embedded in a larger page. Ensure that pages have a concise but descriptive page title, and that dialogs have a concise but descriptive accessible name when the `autofocus` attribute is used on dedicated sign-in pages and dialogs.
+
+Use the `aria-describedby` attribute on elements with `autofocus` so instructions and context are provided for screen reader users.
```html
+<h1 id="signin-passkey">Sign In with Passkey</h1>
<!-- Autocomplete tokens must contain webauthn space-separated -->
<form id="signin-form">
<input
type="text"
name="username"
+ aria-describedby="signin-passkey"
autocomplete="username webauthn"
autofocus
data-testid="username-field"
@@ -74,6 +80,7 @@ Activate form autofill suggestions on page load to offer passkey authentication
5. **Call Signal API**: Wrap server verification `fetch()` call in a try/catch block:
- Show an error message for the user to understand what went wrong.
- Call `signalUnknownCredential()` ONLY when the server explicitly responds with HTTP status `404` (Credential not found) and the user is unauthenticated.
+ - Always pass `rpId: publicKey.rpId` from the server's request options. **DO NOT** derive `rpId` from `window.location.hostname` on the client, as the server's configured RP ID may be a registrable parent domain (such as `example.com` on `login.example.com`) or use Related Origin Requests.
- The `credentialId` parameter passed to `signalUnknownCredential()` MUST strictly be the Base64URL-encoded credential ID string (e.g., `encoded.id`), NOT the raw ArrayBuffer object `credential.rawId`.
6. **Encode the response**: Encode the credential `AuthenticatorAssertionResponse` with `.toJSON()` before sending it to the server for verification.
@@ -106,7 +113,7 @@ async function initializeConditionalAutofill() {
// Note: this code path runs pre-authentication, satisfying the unauth precondition
if (PublicKeyCredential.signalUnknownCredential) {
await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
+ rpId: publicKey.rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
credentialId: encoded.id,
});
}
@@ -154,10 +161,12 @@ async function triggerButtonAuthentication() {
const response = await loginVerifyFetch(encoded);
if (!response.ok && response.status === 404) {
// Note: this code path runs pre-authentication, satisfying the unauth precondition
- await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
- credentialId: encoded.id, // Base64URL-encoded credential ID
- });
+ if (PublicKeyCredential.signalUnknownCredential) {
+ await PublicKeyCredential.signalUnknownCredential({
+ rpId: publicKey.rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
+ credentialId: encoded.id, // Base64URL-encoded credential ID
+ });
+ }
}
} catch (serverErr) {
console.error("Verification request error:", serverErr);
@@ -175,12 +184,14 @@ window.addEventListener("DOMContentLoaded", initializeConditionalAutofill);
Baseline status for the api.PublicKeyCredential.getClientCapabilities_static capability: Newly available. It's been Baseline since 2025-02-06.
Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 135 (Feb 2025), and Safari 17.4 (Mar 2024).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.getClientCapabilities` is also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.getClientCapabilities()` is available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
### Signal API Synchronization Fallback
@@ -197,9 +208,11 @@ The WebAuthn Signal API (`webauthn-signals`) is a progressive optimization used
Baseline status for the api.PublicKeyCredential.parseRequestOptionsFromJSON_static capability: Newly available. It's been Baseline since 2025-03-31.
Supported by: Chrome 129 (Sep 2024), Edge 129 (Sep 2024), Firefox 119 (Oct 2023), and Safari 18.4 (Mar 2025).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.parseRequestOptionsFromJSON` and `PublicKeyCredential.prototype.toJSON` are also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.parseRequestOptionsFromJSON()` and `PublicKeyCredential.prototype.toJSON()` are available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
diff --git a/skills/modern-web-guidance/guides/security/passkey-conditional-create.md b/skills/modern-web-guidance/guides/security/passkey-conditional-create.md
index 4ed96d4..2a05eff 100644
--- a/skills/modern-web-guidance/guides/security/passkey-conditional-create.md
+++ b/skills/modern-web-guidance/guides/security/passkey-conditional-create.md
@@ -26,8 +26,9 @@ if (capabilities.conditionalCreate) {
```
### 3. Create a passkey with Conditional Create
-* Pass `mediation: 'conditional'` within the `navigator.credentials.create()` options. This signals the browser to handle the passkey creation flow silently in the background or contextually without throwing obtrusive modal dialogs.
+* Ensure the server's registration options endpoint includes the predefined RP ID in `rp.id` so `publicKey.rp.id` is populated if `PublicKeyCredential.signalUnknownCredential()` runs in Step 6, because omitting `rp.id` in WebAuthn creation options leaves `publicKey.rp.id` undefined on the client.
* Populate `excludeCredentials` with the user's existing passkey credential IDs to avoid registering duplicate keys.
+* Pass `mediation: 'conditional'` within the `navigator.credentials.create()` options. This signals the browser to handle the passkey creation flow silently in the background or contextually without throwing obtrusive modal dialogs.
### 4. Silent Error Handling
* Wrap the passkey creation prompt (`navigator.credentials.create`) in a try/catch block. You MUST catch and silently ignore typical user-facing exceptions (`InvalidStateError`, `NotAllowedError`, `AbortError`) without rendering any error UI to the user.
@@ -36,7 +37,7 @@ if (capabilities.conditionalCreate) {
* The server-side verification endpoint MUST relax the User Presence (UP) requirement (`requireUserPresence: false`) **ONLY** when verifying credentials produced by a conditional-create trigger. Strict presence verification must remain active for standard explicit creations.
### 6. Handle Failed Server Verification gracefully
-* If `navigator.credentials.create()` succeeds but the server verification fetch returns a bad response (e.g., signature verification fails), invoke `PublicKeyCredential.signalUnknownCredential()` to prevent orphaned credentials from lingering in the passkey provider.
+* If `navigator.credentials.create()` succeeds but the server verification fetch returns a bad response (e.g., signature verification fails), invoke `PublicKeyCredential.signalUnknownCredential({ rpId: publicKey.rp.id, credentialId: encodedResponse.id })` to prevent orphaned credentials from lingering in the passkey provider. Always read `rpId` from `publicKey.rp.id` in the server's creation options; **DO NOT** derive `rpId` from `window.location.hostname` on the client, which can mismatch a parent-domain or related-origin RP ID.
## Code Example
@@ -53,7 +54,7 @@ async function triggerConditionalCreate(loginAbortController) {
// 1. Abort any active autofill conditional-get controllers to clear the WebAuthn pipeline
loginAbortController.abort();
- // 2. Fetch creation options signaling the backend that this is a conditional request
+ // 2. Fetch creation options signaling the backend that this is a conditional request (server options must include rp.id)
const creationOptionsJSON = await optionsFetch({ conditional: true });
const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON(creationOptionsJSON);
@@ -81,7 +82,7 @@ async function triggerConditionalCreate(loginAbortController) {
// If the server verification fails, clean up using Signal API
if (PublicKeyCredential.signalUnknownCredential) {
await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
+ rpId: publicKey.rp.id, // Always use the server-provided rp.id; DO NOT use window.location.hostname
credentialId: encodedResponse.id
});
}
@@ -90,7 +91,7 @@ async function triggerConditionalCreate(loginAbortController) {
console.error('Verification network failure:', serverErr);
if (PublicKeyCredential.signalUnknownCredential) {
await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
+ rpId: publicKey.rp.id, // Always use the server-provided rp.id; DO NOT use window.location.hostname
credentialId: encodedResponse.id
});
}
@@ -105,12 +106,14 @@ async function triggerConditionalCreate(loginAbortController) {
Baseline status for the api.PublicKeyCredential.getClientCapabilities_static capability: Newly available. It's been Baseline since 2025-02-06.
Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 135 (Feb 2025), and Safari 17.4 (Mar 2024).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.getClientCapabilities` is also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.getClientCapabilities()` is available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
### Signal API Synchronization Fallback
@@ -126,9 +129,11 @@ The WebAuthn Signal API (`webauthn-signals`) is a progressive optimization used
Baseline status for the api.PublicKeyCredential.parseCreationOptionsFromJSON_static capability: Newly available. It's been Baseline since 2025-03-31.
Supported by: Chrome 129 (Sep 2024), Edge 129 (Sep 2024), Firefox 119 (Oct 2023), and Safari 18.4 (Mar 2025).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.parseCreationOptionsFromJSON` and `PublicKeyCredential.prototype.toJSON` are also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.parseCreationOptionsFromJSON()` and `PublicKeyCredential.prototype.toJSON()` are available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
diff --git a/skills/modern-web-guidance/guides/security/passkey-management.md b/skills/modern-web-guidance/guides/security/passkey-management.md
index 1375dc2..65e33d4 100644
--- a/skills/modern-web-guidance/guides/security/passkey-management.md
+++ b/skills/modern-web-guidance/guides/security/passkey-management.md
@@ -6,16 +6,22 @@ This guide details how to enable users to view, rename, and delete their registe
Your backend database layer and endpoints MUST support common CRUD actions for registered credentials as well as updating user profile details. Decoupled from framework-specific libraries, the server exposes endpoints to:
-1. **List all user credentials**: Fetch all `StoredPasskeyCredential` records matching the signed-in user's ID.
+1. **List all user credentials**: Fetch all `StoredPasskeyCredential` records matching the signed-in user's ID, and return them alongside the server's configured `rpId` and the user's `passkeyUserId` so the client never has to guess `rpId` from `window.location.hostname`. Ensure every credential `id` and user `passkeyUserId` is stored and returned as a valid unpadded Base64URL string (`[A-Za-z0-9_-]`, no `=` padding, and `length % 4 !== 1`)—including in prototype seed data and mock backends (for example, `Buffer.from('cred-1').toString('base64url')` or `'dGVzdC1jcmVkLTE'`, never arbitrary human-readable placeholders like `'passkey-1'` or `'cred_yubikey_01'`).
2. **Update credential names**: Accept a new custom nickname for a specific credential ID and persist the update on the server.
3. **Delete credentials**: Remove a specific credential ID from the database.
-4. **Update user account details**: Accept updated `name` (username) and `displayName` values for the signed-in user's profile so the client can synchronize them with the passkey provider.
+4. **Update user account details**: Accept updated `name` (username) and `displayName` values for the signed-in user's profile and return the updated user profile alongside the server's `rpId` and Base64URL `passkeyUserId` so the client can synchronize them with the passkey provider.
```javascript
// Node.js routing example for credential CRUD and user profile rename
+const RP_ID = 'example.com'; // Predefined server RP ID (example value; must match registration rp.id)
+
router.get('/api/credentials', checkUserAuthenticated, async (req, res) => {
- const list = await db.findCredentialsByUserId(req.user.id);
- return res.json(list);
+ const credentials = await db.findCredentialsByUserId(req.user.id);
+ return res.json({
+ rpId: RP_ID,
+ userId: req.user.passkeyUserId, // Valid unpadded Base64URL string
+ credentials,
+ });
});
router.put('/api/credential/:id', checkUserAuthenticated, async (req, res) => {
@@ -43,7 +49,11 @@ router.delete('/api/credential/:id', checkUserAuthenticated, async (req, res) =>
router.put('/api/user', checkUserAuthenticated, async (req, res) => {
const { name, displayName } = req.body;
const updatedUser = await db.updateUser(req.user.id, { name, displayName });
- return res.json(updatedUser);
+ return res.json({
+ ...updatedUser,
+ rpId: RP_ID,
+ userId: updatedUser.passkeyUserId,
+ });
});
```
@@ -70,55 +80,72 @@ Render a dedicated settings panel allowing users to easily audit and manage thei
The Signal API lets the application communicate credential states to password managers, keeping the user's synced vaults and your backend database in lockstep.
+> [!IMPORTANT]
+> Browsers strictly validate Base64URL encoding and string length (`length % 4 !== 1`, characters strictly `[A-Za-z0-9_-]`, no `=` padding) in native code. Passing arbitrary human-readable placeholder or mock IDs (such as `'passkey-1'`, `'cred:01'`, or unencoded strings like `'cred_yubikey_01'`) throws `TypeError: Invalid base64url string for allAcceptedCredentialIds` on page load. Always encode mock/test IDs as genuine unpadded Base64URL strings (for example, `'dGVzdC1jcmVkLTE'` or `Buffer.from('cred-1').toString('base64url')`) and validate format before invoking the Signal API.
+
+* **Use the Server-Provided `rpId` (DO NOT Use `window.location.hostname`)**:
+ * Always pass the `rpId` returned by your backend API (matching the `rp.id` used when registering passkeys). **DO NOT** derive `rpId` from `window.location.hostname` on the client: when credentials are registered to a registrable parent domain (for example, `example.com` while the settings page is served on `accounts.example.com`) or shared via Related Origin Requests (`/.well-known/webauthn`), `window.location.hostname` will not match the credential's RP ID, causing password manager synchronization to silently target the wrong RP ID or throw a `SecurityError`.
* **Feature Detection & Parameter Encoding Rule**:
* Always feature-detect Signal API methods before invoking them (`if (PublicKeyCredential.signalAllAcceptedCredentials)` and `if (PublicKeyCredential.signalCurrentUserDetails)`).
- * All `userId` and credential ID parameters passed to Signal API methods (`signalAllAcceptedCredentials`, `signalCurrentUserDetails`) MUST be **Base64URL-encoded strings**.
+ * All `userId` and credential ID parameters passed to Signal API methods (`signalAllAcceptedCredentials`, `signalCurrentUserDetails`) MUST be **valid unpadded Base64URL-encoded strings**. Validate `userId` and `allAcceptedCredentialIds` before calling the API so malformed IDs are skipped safely rather than throwing on load.
* **Initiating Page Load Sync**:
* The application MUST invoke `signalAllAcceptedCredentials()` automatically when the management page loads (for example, inside a `DOMContentLoaded` event listener, module initialization, or framework component mount hook such as `useEffect`).
* **Management Updates Sync**:
* The application MUST invoke `signalAllAcceptedCredentials()` immediately within your delete credential click handler post-fetch.
* The application MUST invoke `signalCurrentUserDetails()` immediately within your user account rename (`name` or `displayName`) click handler post-fetch.
+* **Non-Fatal Error Handling (`console.warn`)**:
+ * Signal API calls perform passive background synchronization and MUST NOT break the UI or emit `console.error` when synchronization fails. Wrap Signal API calls in `try...catch` and log failures with `console.warn` instead of `console.error` so passive sync issues do not trigger Lighthouse Best Practices failures (`errors-in-console`) on page load.
```javascript
// Client-side management synchronization ES module
import { listFetch, renameCredentialFetch, updateUserFetch, deleteFetch } from './api.js';
-// Base64URL-encoded User ID string (illustration only)
-const base64UrlUserId = "M2YPl-KGnA8";
+// Valid unpadded Base64URL: non-empty, [A-Za-z0-9_-] only, no '=' padding, length % 4 !== 1
+function isValidBase64Url(value) {
+ return typeof value === 'string' &&
+ value.length > 0 &&
+ value.length % 4 !== 1 &&
+ /^[A-Za-z0-9_-]+$/.test(value);
+}
-async function syncAcceptedCredentials(currentCredentialsList) {
+async function syncAcceptedCredentials(rpId, userId, currentCredentialsList) {
if (!window.PublicKeyCredential || !PublicKeyCredential.signalAllAcceptedCredentials) return;
+ const credentialIds = currentCredentialsList.map(c => c.id); // Array of Base64URL credential ID strings
+ if (!rpId || !isValidBase64Url(userId) || !credentialIds.every(isValidBase64Url)) {
+ console.warn('SignalAllAcceptedCredentials skipped: server rpId and valid unpadded Base64URL userId and credential IDs are required.');
+ return;
+ }
+
try {
- const credentialIds = currentCredentialsList.map(c => c.id); // Array of Base64URL credential ID strings
-
await PublicKeyCredential.signalAllAcceptedCredentials({
- rpId, // RP ID must match the one defined on the server
- userId: base64UrlUserId, // User ID Base64URL-encoded string
+ rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
+ userId, // Base64URL-encoded user ID from the server
allAcceptedCredentialIds: credentialIds
});
} catch (e) {
- console.error('SignalAllAcceptedCredentials sync failure:', e);
+ // Use console.warn instead of console.error so passive sync failures do not fail Lighthouse errors-in-console
+ console.warn('SignalAllAcceptedCredentials sync warning:', e);
}
}
async function loadManagementPanel() {
const response = await listFetch();
- const list = await response.json();
+ const { rpId, userId, credentials } = await response.json();
- renderUI(list);
- // Sync accepted credentials on initial load
- await syncAcceptedCredentials(list);
+ renderUI(credentials);
+ // Sync accepted credentials on initial load using server-provided rpId and userId
+ await syncAcceptedCredentials(rpId, userId, credentials);
}
async function performDelete(credentialId) {
const response = await deleteFetch(credentialId);
if (response.ok) {
const updatedResponse = await listFetch();
- const updatedList = await updatedResponse.json();
+ const { rpId, userId, credentials } = await updatedResponse.json();
- renderUI(updatedList);
+ renderUI(credentials);
// Sync remaining accepted credentials after deletion
- await syncAcceptedCredentials(updatedList);
+ await syncAcceptedCredentials(rpId, userId, credentials);
}
}
@@ -127,23 +154,30 @@ async function performCredentialRename(credentialId, newCredentialName) {
const response = await renameCredentialFetch(credentialId, { name: newCredentialName });
if (response.ok) {
const updatedResponse = await listFetch();
- renderUI(await updatedResponse.json());
+ const { credentials } = await updatedResponse.json();
+ renderUI(credentials);
}
}
// Renaming the user's account username or displayName triggers signalCurrentUserDetails
-async function performUserRename(rpId, userId, updatedName, updatedDisplayName) {
+async function performUserRename(updatedName, updatedDisplayName) {
const response = await updateUserFetch({ name: updatedName, displayName: updatedDisplayName });
if (response.ok && window.PublicKeyCredential && PublicKeyCredential.signalCurrentUserDetails) {
+ const { rpId, userId } = await response.json();
+ if (!rpId || !isValidBase64Url(userId)) {
+ console.warn('SignalCurrentUserDetails skipped: server rpId and valid unpadded Base64URL userId are required.');
+ return;
+ }
try {
await PublicKeyCredential.signalCurrentUserDetails({
- rpId, // RP ID must match the one defined on the server
- userId, // Base64URL-encoded user ID
+ rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
+ userId, // Base64URL-encoded user ID from the server
name: updatedName, // Updated username
displayName: updatedDisplayName // Updated display name
});
} catch (e) {
- console.error('SignalCurrentUserDetails sync failure:', e);
+ // Use console.warn instead of console.error for passive background sync
+ console.warn('SignalCurrentUserDetails sync warning:', e);
}
}
}
@@ -209,11 +243,34 @@ if (aaguid === '00000000-0000-0000-0000-000000000000') {
Baseline status for the api.PublicKeyCredential.getClientCapabilities_static capability: Newly available. It's been Baseline since 2025-02-06.
Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 135 (Feb 2025), and Safari 17.4 (Mar 2024).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.getClientCapabilities` is also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.getClientCapabilities()` is available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
+
+Before rendering the "Create passkey" button, call `PublicKeyCredential.getClientCapabilities()` to verify platform authenticator support, and hide the button when unsupported:
+
+```javascript
+async function isPasskeySupported() {
+ if (!window.PublicKeyCredential || !PublicKeyCredential.getClientCapabilities) {
+ return false;
+ }
+ try {
+ const capabilities = await PublicKeyCredential.getClientCapabilities();
+ return Boolean(capabilities.passkeyPlatformAuthenticator);
+ } catch {
+ return false;
+ }
+}
+
+const createButton = document.getElementById('create-passkey');
+if (!(await isPasskeySupported())) {
+ createButton.hidden = true;
+}
```
### Signal API Synchronization Fallback
@@ -222,15 +279,32 @@ Browser support for Web authentication signal methods: Limited availability.
Supported by: Chrome 132 (Jan 2025), Edge 132 (Jan 2025), and Safari 26 (Sep 2025).
Unsupported in: Firefox.
-If the browser does not support `PublicKeyCredential.parseRequestOptionsFromJSON`, use the 'webauthn-polyfills':
-
-```html
-<script type="module">
- if (!PublicKeyCredential.parseRequestOptionsFromJSON) {
- await import('https://unpkg.com/webauthn-polyfills');
- }
- </script>
-```
+The WebAuthn Signal API (`webauthn-signals`) is a progressive enhancement that synchronizes server-side credential deletions and account profile updates with the user's password manager. Because synchronization communicates directly with the browser or OS passkey provider, no polyfill is available if your Baseline target does not support `webauthn-signals`. Gate calls behind static feature detection on `PublicKeyCredential` so unsupported browsers skip background synchronization safely while server-side passkey listing, renaming, deletion, and user profile updates continue to work normally without throwing browser exceptions:
-This will also add support for `PublicKeyCredential.prototype.toJSON`.
+```javascript
+if (window.PublicKeyCredential && PublicKeyCredential.signalAllAcceptedCredentials) {
+ try {
+ await PublicKeyCredential.signalAllAcceptedCredentials({
+ rpId, // Server-provided RP ID (never window.location.hostname)
+ userId, // Valid unpadded Base64URL user ID
+ allAcceptedCredentialIds: credentialIds, // Valid unpadded Base64URL credential IDs
+ });
+ } catch (e) {
+ console.warn('SignalAllAcceptedCredentials sync warning:', e);
+ }
+}
+
+if (window.PublicKeyCredential && PublicKeyCredential.signalCurrentUserDetails) {
+ try {
+ await PublicKeyCredential.signalCurrentUserDetails({
+ rpId, // Server-provided RP ID (never window.location.hostname)
+ userId, // Valid unpadded Base64URL user ID
+ name: updatedName,
+ displayName: updatedDisplayName,
+ });
+ } catch (e) {
+ console.warn('SignalCurrentUserDetails sync warning:', e);
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/security/passkey-reauthentication.md b/skills/modern-web-guidance/guides/security/passkey-reauthentication.md
index 178931d..64b1a77 100644
--- a/skills/modern-web-guidance/guides/security/passkey-reauthentication.md
+++ b/skills/modern-web-guidance/guides/security/passkey-reauthentication.md
@@ -45,7 +45,7 @@ Applications choose from two reauthentication interfaces depending on the transa
### A. Button Flow (No Input Fields)
-Trigger reauthentication when a user presses a "Verify Identity" or "Proceed with Transaction" button.
+Trigger reauthentication when a user presses a "Verify Identity" or "Proceed with Transaction" button. When signaling an unknown credential on HTTP `404`, always pass `rpId: publicKey.rpId` from the server's request options—**DO NOT** derive `rpId` from `window.location.hostname` on the client.
```html
<button id="reauth-btn" data-testid="reauth-button">Confirm Transaction</button>
@@ -84,7 +84,7 @@ async function triggerButtonReauth() {
showTransactionSuccessUI();
} else if (verifyResponse.status === 404 && PublicKeyCredential.signalUnknownCredential) {
await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
+ rpId: publicKey.rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
credentialId: encodedCredential.id
});
}
@@ -108,21 +108,35 @@ document
Baseline status for the api.PublicKeyCredential.getClientCapabilities_static capability: Newly available. It's been Baseline since 2025-02-06.
Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 135 (Feb 2025), and Safari 17.4 (Mar 2024).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.getClientCapabilities` is also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.getClientCapabilities()` is available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
+
+### Signal API Synchronization Fallback
+
+Browser support for Web authentication signal methods: Limited availability.
+Supported by: Chrome 132 (Jan 2025), Edge 132 (Jan 2025), and Safari 26 (Sep 2025).
+Unsupported in: Firefox.
+
+The WebAuthn Signal API (`webauthn-signals`) is a progressive optimization used to keep password managers in sync with the server credential state.
+
+- **Fallback Experience**: Gate calls behind `if (PublicKeyCredential.signalUnknownCredential)`. If unsupported, the background verification sync is bypassed gracefully without throwing browser exceptions.
### Easy JSON Serialization Fallback
Baseline status for the api.PublicKeyCredential.parseRequestOptionsFromJSON_static capability: Newly available. It's been Baseline since 2025-03-31.
Supported by: Chrome 129 (Sep 2024), Edge 129 (Sep 2024), Firefox 119 (Oct 2023), and Safari 18.4 (Mar 2025).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.parseRequestOptionsFromJSON` and `PublicKeyCredential.prototype.toJSON` are also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.parseRequestOptionsFromJSON()` and `PublicKeyCredential.prototype.toJSON()` are available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
diff --git a/skills/modern-web-guidance/guides/security/passkey-registration.md b/skills/modern-web-guidance/guides/security/passkey-registration.md
index e260d10..fbc0d0a 100644
--- a/skills/modern-web-guidance/guides/security/passkey-registration.md
+++ b/skills/modern-web-guidance/guides/security/passkey-registration.md
@@ -30,7 +30,7 @@ export interface StoredPasskeyCredential {
Create an endpoint that generates WebAuthn creation parameters. Rely on a vetted library per category standards instead of hand-rolling cryptography.
-1. **Use the predefined RP ID**: Use the predefined proper RP ID as a constant string.
+1. **Use the predefined RP ID**: Use the predefined proper RP ID as a constant string in `rp.id` so the client can pass `publicKey.rp.id` directly to Signal API calls.
2. **Create a secure Challenge**: Generate a high-entropy, cryptographically secure random buffer on the server, store it securely in the user's session, and encode it as Base64URL for options delivery.
3. **Avoid Duplicate Passkeys**: Map the user's existing pre-registered credential IDs to the `excludeCredentials` options array. This prevents the authenticator from registering duplicate credentials on the same passkey provider account.
4. **Enforce Discoverable Credentials**: Set `requireResidentKey: true` and `residentKey: "required"` in the `authenticatorSelection` options to request a discoverable credential, which is necessary for discoverable sign-ins.
@@ -94,7 +94,8 @@ const options = {
- `AbortError`: The operation has been aborted.
- `SecurityError`: Secure origins (HTTPS) or RP ID mismatch errors (configuration issues).
4. **Try/Catch Segregation for Signal API**:
- - Wrap server verification `fetch()` call in a try/catch block. Call `signalUnknownCredential()` when the server verification fetch fails (any status `response.ok === false` or network throws).
+ - Wrap server verification `fetch()` call in a try/catch block. Call `PublicKeyCredential.signalUnknownCredential({ rpId: publicKey.rp.id, credentialId: encodedResponse.id })` (gated on `if (PublicKeyCredential.signalUnknownCredential)`) when the server verification fetch fails (any status `response.ok === false` or network throws).
+ - Always read `rpId` from `publicKey.rp.id` in the server's creation options. **DO NOT** derive `rpId` from `window.location.hostname` on the client, as the server's configured RP ID may be a registrable parent domain (such as `example.com` on `accounts.example.com`) or use Related Origin Requests.
```javascript
// optionsFetch and registerVerifyFetch are app-defined HTTP methods
@@ -136,22 +137,24 @@ async function registerPasskey(isPromotion = false) {
}
// Server Verification phase (Segregated Try/Catch)
- let encodedResponse = credential.toJSON();
+ const encodedResponse = credential.toJSON();
try {
const response = await registerVerifyFetch(encodedResponse);
- if (!response.ok) {
+ if (!response.ok && PublicKeyCredential.signalUnknownCredential) {
// Server verification failed to verify/authenticate the credential (orphaned)
await PublicKeyCredential.signalUnknownCredential({
- rpId, // RP ID must match the one defined on the server
+ rpId: publicKey.rp.id, // Always use the server-provided rp.id; DO NOT use window.location.hostname
credentialId: encodedResponse.id, // Base64URL-encoded credential ID
});
}
} catch (serverErr) {
console.error("Server verification network failure:", serverErr);
- await publickeycredential.signalunknowncredential({
- rpId, // RP ID must match the one defined on the server
- credentialid: encodedresponse.id, // base64url-encoded credential id
- });
+ if (PublicKeyCredential.signalUnknownCredential) {
+ await PublicKeyCredential.signalUnknownCredential({
+ rpId: publicKey.rp.id, // Always use the server-provided rp.id; DO NOT use window.location.hostname
+ credentialId: encodedResponse.id, // Base64URL-encoded credential ID
+ });
+ }
}
}
```
@@ -173,9 +176,11 @@ The WebAuthn Signal API (`webauthn-signals`) is a progressive optimization used
Baseline status for the api.PublicKeyCredential.parseCreationOptionsFromJSON_static capability: Newly available. It's been Baseline since 2025-03-31.
Supported by: Chrome 129 (Sep 2024), Edge 129 (Sep 2024), Firefox 119 (Oct 2023), and Safari 18.4 (Mar 2025).
-Always install 'webauthn-polyfills' and import it in the context.
-Consider as long as `PublicKeyCredential` is supported, `PublicKeyCredential.parseCreationOptionsFromJSON` and `PublicKeyCredential.prototype.toJSON` are also supported.
+Load `webauthn-polyfills` so `PublicKeyCredential.parseCreationOptionsFromJSON()` and `PublicKeyCredential.prototype.toJSON()` are available whenever `PublicKeyCredential` is supported:
-```js
+```js
+// With a bundler (`npm install webauthn-polyfills`):
import 'webauthn-polyfills';
-```
+```
+
+Without a bundler, serve the package from your own origin, or import it from a CDN such as `https://esm.sh/[email protected]` (pin the exact version). For third-party URLs, add Subresource Integrity: the `integrity` attribute on the `<script>` tag, or an import map's `integrity` field for `import` statements.
diff --git a/skills/modern-web-guidance/guides/security/passkeys.md b/skills/modern-web-guidance/guides/security/passkeys.md
index be2df60..f002798 100644
--- a/skills/modern-web-guidance/guides/security/passkeys.md
+++ b/skills/modern-web-guidance/guides/security/passkeys.md
@@ -6,7 +6,7 @@ This guide provides high-density, action-oriented orientation for implementing s
Passkeys rely on the Web Authentication API (WebAuthn), which imposes strict cross-cutting security constraints that must be satisfied before any implementation attempt:
* **Secure Contexts**: WebAuthn methods (`navigator.credentials.create` and `navigator.credentials.get`) are strictly gated behind Secure Contexts. Applications MUST run on `https://` in production, or `http://localhost` for local development.
-* **Relying Party (RP) ID**: Every credential is tied to an RP ID (essentially the domain name of the application). The RP ID passed in the server-side options MUST match or be a valid suffix of the current origin's domain name (e.g., `example.com` is valid for `login.example.com`). Mismatches result in `SecurityError` exceptions on the client side.
+* **Relying Party (RP) ID**: Every credential is tied to an RP ID (essentially the domain name of the application). The RP ID passed in the server-side options MUST match or be a valid registrable domain suffix of the current origin's domain name (e.g., `example.com` is valid for `login.example.com`), or be authorized via Related Origin Requests (`/.well-known/webauthn`). Mismatches result in `SecurityError` exceptions on the client side. **DO NOT** derive `rpId` from `window.location.hostname` on the client (for example, when calling WebAuthn Signal API methods), because `window.location.hostname` will not match a parent-domain or related-origin RP ID configured on the server; always read `rpId` from the server-provided WebAuthn options (`publicKey.rp.id` or `publicKey.rpId`) or backend API responses.
## 2. The AAGUID UX Caveat
diff --git a/skills/modern-web-guidance/guides/security/quick-sign-ins.md b/skills/modern-web-guidance/guides/security/quick-sign-ins.md
index a9ba473..251aa89 100644
--- a/skills/modern-web-guidance/guides/security/quick-sign-ins.md
+++ b/skills/modern-web-guidance/guides/security/quick-sign-ins.md
@@ -35,9 +35,10 @@ Browsers enforce strict privacy and security rules when `uiMode: 'immediate'` is
Expose an endpoint that generates discoverable WebAuthn request options for unauthenticated visitors:
-1. **Generate a session-bound challenge**: Create a cryptographically random challenge buffer, store it in the server session, and encode it as Base64URL.
-2. **Persist user verification preference**: Set `userVerification: 'preferred'` and store `expectedUserVerification: 'preferred'` in the session.
-3. **Omit `allowCredentials`**: Do not include a non-empty `allowCredentials` list in the options for Immediate UI mode, as browsers reject non-empty allowlists with `NotAllowedError`.
+1. **Include the server's predefined `rpId`**: Set `rpId` explicitly in the request options (matching the RP ID used during passkey registration) so the client can pass `publicKey.rpId` directly to Signal API calls.
+2. **Generate a session-bound challenge**: Create a cryptographically random challenge buffer, store it in the server session, and encode it as Base64URL.
+3. **Persist user verification preference**: Set `userVerification: 'preferred'` and store `expectedUserVerification: 'preferred'` in the session.
+4. **Omit `allowCredentials`**: Do not include a non-empty `allowCredentials` list in the options for Immediate UI mode, as browsers reject non-empty allowlists with `NotAllowedError`.
```javascript
// Server-side options generation example (/api/login/options)
@@ -67,9 +68,10 @@ Because `navigator.credentials.get({ password: true, publicKey, uiMode: 'immedia
1. **Request both passkeys and passwords**: Decode the server options using `PublicKeyCredential.parseRequestOptionsFromJSON()` and call `navigator.credentials.get()` inside a user-initiated click handler with `password: true`, `publicKey`, and `uiMode: 'immediate'` (without passing `signal`).
2. **Branch verification by `cred.type`**:
- - If `cred.type === 'public-key'`, serialize the assertion with `cred.toJSON()` and POST it to your WebAuthn verification endpoint. When the server responds with HTTP `404`, call `PublicKeyCredential.signalUnknownCredential({ rpId: publicKey.rpId, credentialId: encoded.id })`.
+ - If `cred.type === 'public-key'`, serialize the assertion with `cred.toJSON()` and POST it to your WebAuthn verification endpoint. When the server responds with HTTP `404`, call `PublicKeyCredential.signalUnknownCredential({ rpId: publicKey.rpId, credentialId: encoded.id })`. Always use `publicKey.rpId` from the server's request options—**DO NOT** derive or fall back to `window.location.hostname` on the client, as the server's configured RP ID may be a registrable parent domain (such as `example.com` on `shop.example.com`) or use Related Origin Requests.
- If `cred.type === 'password'`, POST `{ username: cred.id, password: cred.password }` to your password verification endpoint.
-3. **Handle `NotAllowedError` when no local credentials exist**: Catch `NotAllowedError` (thrown immediately when no local passkeys or saved passwords exist on the device, or when the user dismisses the chooser) and transition to your standard sign-in flow (such as opening an inline sign-in dialog or navigating to `/signin` with a return URL).
+3. **Handle `NotAllowedError` when no local credentials exist**: Catch `NotAllowedError` (thrown immediately when no local passkeys or saved passwords exist on the device, or when the user dismisses the chooser) and transition to your standard sign-in flow (such as opening an inline sign-in dialog or navigating to `/signin` with a return URL). When revealing an inline fallback sign-in form or dialog in place, move focus to its first interactive control and announce the state change via a polite live region (`role="status"`).
+4. **Restore focus and announce in-place sign-in completion**: When in-place authentication or fallback form submission hides the sign-in trigger or inline form, restore focus to the originating action control (or to a surviving authenticated control in the header) so keyboard focus does not drop to `document.body`, and announce the authenticated state in a status live region (`role="status"`).
```javascript
let isAuthenticating = false;
@@ -102,10 +104,12 @@ async function authenticateWithImmediateUi() {
});
if (verifyResponse.status === 404) {
- await PublicKeyCredential.signalUnknownCredential({
- rpId: publicKey.rpId || window.location.hostname,
- credentialId: encoded.id, // Base64URL-encoded credential ID string
- });
+ if (PublicKeyCredential.signalUnknownCredential) {
+ await PublicKeyCredential.signalUnknownCredential({
+ rpId: publicKey.rpId, // Always use the server-provided rpId; DO NOT use window.location.hostname
+ credentialId: encoded.id, // Base64URL-encoded credential ID string
+ });
+ }
throw new Error('Passkey credential is no longer recognized by the server');
}
@@ -151,15 +155,17 @@ favoriteButton.addEventListener('click', async (event) => {
isAuthenticating = true;
try {
const user = await authenticateWithImmediateUi();
- // Complete the user's intended action immediately
+ // Complete the user's intended action immediately, restore focus so hiding
+ // sign-in UI does not drop focus to document.body, and announce status
document.body.dataset.signedIn = 'true';
favoriteButton.setAttribute('aria-pressed', 'true');
updateHeaderUserState(user);
+ favoriteButton.focus();
} catch (err) {
if (err.name === 'NotAllowedError') {
// No local credentials available or user dismissed dialog:
- // transition smoothly to fallback sign-in UI or redirect with return URL
- showFallbackSignInUi({ returnAction: 'favorite' });
+ // reveal fallback sign-in UI (moving focus to its first input) or redirect with return URL
+ showFallbackSignInUi({ returnAction: 'favorite', returnFocusEl: favoriteButton });
return;
}
console.error('Authentication error:', err);
diff --git a/skills/modern-web-guidance/guides/security/restrict-outbound-connections.md b/skills/modern-web-guidance/guides/security/restrict-outbound-connections.md
index b33393e..1e83d1a 100644
--- a/skills/modern-web-guidance/guides/security/restrict-outbound-connections.md
+++ b/skills/modern-web-guidance/guides/security/restrict-outbound-connections.md
@@ -6,7 +6,7 @@ The `Connection-Allowlist` HTTP response header restricts a document or worker t
1. **Serialize the allowlist as an RFC 9651 Inner List `(...)`**: Format `Connection-Allowlist` (or `Connection-Allowlist-Report-Only`) as a single parenthesized list of space-separated items. Include the unquoted token `response-origin` to permit the document or worker's own origin, followed by double-quoted `URLPattern` strings for every legitimate external endpoint the context connects or navigates to (APIs, image/font CDNs, and outbound `<a href>`, `<form action>`, OAuth, or payment redirect targets). When building patterns dynamically from configuration or `URL` objects, normalize `ws:`/`wss:` to `http:`/`https:` and strip bare trailing slashes on origin-only URLs (because `new URL('https://api.example.com').href` appends `/`, which restricts `URLPattern` matching to the root path `/` only).
2. **Scope middleware by `Sec-Fetch-Dest` and cover workers**: Browsers only honor `Connection-Allowlist` on document/navigation responses and worker script responses (`Sec-Fetch-Dest` values `document`, `iframe`, `worker`, `sharedworker`, and `serviceworker`). When varying headers by `Sec-Fetch-Dest`, include `Vary: Sec-Fetch-Dest` so shared caches do not serve headerless responses. Serve a matching allowlist on Dedicated and Shared Worker scripts so compromised page scripts cannot exfiltrate data via `worker.postMessage()`. Because a Service Worker performs its own network fetches on cache misses and navigation preloads, configure its `Connection-Allowlist` as a **superset** of the allowlists of all documents it controls.
-3. **Configure violation reporting and staged or dual rollout**: Define a `Reporting-Endpoints` header and append an unquoted `; report-to=<endpoint-name>` parameter after the closing `)`. You can send `Connection-Allowlist-Report-Only` alone during initial rollout, or send **both** `Connection-Allowlist` (enforcing a baseline allowlist) and `Connection-Allowlist-Report-Only` (auditing a stricter candidate allowlist) on the same response. Violation reports are delivered with `"type": "connection-allowlist"` and body `{ url, connection, allowlist, disposition }` (where `connection` is the blocked destination URL or `"webrtc"`, and `disposition` is `"enforce"` or `"report"`).
+3. **Always configure violation reporting (`Reporting-Endpoints` and `report-to`) and support staged or dual rollout**: Define a `Reporting-Endpoints` header and append an unquoted `; report-to=<endpoint-name>` parameter after the closing `)` on every `Connection-Allowlist` or `Connection-Allowlist-Report-Only` policy so blocked connection attempts are observable. You can send `Connection-Allowlist-Report-Only` alone during initial rollout, or send **both** `Connection-Allowlist` (enforcing a baseline allowlist) and `Connection-Allowlist-Report-Only` (auditing a stricter candidate allowlist) on the same response. Violation reports are delivered with `"type": "connection-allowlist"` and body `{ url, connection, allowlist, disposition }` (where `connection` is the blocked destination URL or `"webrtc"`, and `disposition` is `"enforce"` or `"report"`).
4. **Account for default redirect and WebRTC blocking, and handle client errors**: By default, `Connection-Allowlist` blocks all `3xx` HTTP redirects (`redirects=block`, even when redirecting between allowlisted or same-origin URLs) and all `RTCPeerConnection` traffic (`webrtc=block`). Append `; redirects=allow` only when trusted endpoints require server-side redirects (the initial request must still match the allowlist), or `; webrtc=allow` when WebRTC is required. On the client, wrap outbound `fetch()` calls in `try...catch` and handle `WebSocket` `error` events so requests rejected with `TypeError` (`net::ERR_NETWORK_ACCESS_REVOKED`) return a handled error state and update UI status instead of causing unhandled rejections.
## Example code
diff --git a/skills/modern-web-guidance/guides/security/security.md b/skills/modern-web-guidance/guides/security/security.md
index 364926e..6fa7247 100644
--- a/skills/modern-web-guidance/guides/security/security.md
+++ b/skills/modern-web-guidance/guides/security/security.md
@@ -78,7 +78,7 @@ Trusted Types can enforce this pattern at runtime by blocking string assignments
Ensure session and application cookies are configured securely by default, whether set via `Set-Cookie` headers or framework session configuration (such as Astro or Express session middleware).
- **DO**: Name first-party session cookies with the `__Host-` prefix (`name: '__Host-session'`) when used by a single domain. This requires `Secure` (`secure: true`), `Path=/` (`path: '/'`), and omitting the `Domain` attribute, protecting against same-site and network attackers.
- **DO**: Prefer naming cookies with the `__Secure-` prefix when `__Host-` isn't appropriate. This requires the `Secure` attribute, and protects against network attackers.
-- **DO**: Set `HttpOnly` (`httpOnly: true`) on session and authentication cookies unless the cookie must be read by client-side script, and explicitly set `SameSite=Lax` (`sameSite: 'lax'`) for standard first-party cookies.
+- **DO**: Set `HttpOnly` (`httpOnly: true`) on session and authentication cookies so they cannot be read by injected client-side scripts, and explicitly set `SameSite=Lax` (`sameSite: 'lax'`) for standard first-party cookies.
- **DO**: If your application will be embedded as an iframe in third-party contexts, use `SameSite=None; Secure; Partitioned`.
- **DO NOT**: Rely on unpartitioned `SameSite=None` — these are being systematically blocked for tracking prevention.
@@ -285,7 +285,7 @@ Lowest-risk of the three. Deploy if the app is **not** an OAuth provider, paymen
Set CORP explicitly on each response based on whether it should be embeddable in other contexts. Two core benefits: it protects resources from malicious cross-origin reads, and ensures compatibility when pages request stronger client-side isolation.
-- **DO**: Default to `Cross-Origin-Resource-Policy: same-origin` for app-internal resources (authenticated data, user session JSON, restricted internal scripts).
+- **DO**: Default to `Cross-Origin-Resource-Policy: same-origin` for app-internal responses (such as HTML documents, internal endpoints, authenticated data, user session JSON, and restricted internal scripts).
- **DO**: Use `same-site` for endpoints utilized across subdomains of the same eTLD+1.
- **DO**: Provide `cross-origin` exclusively for resources created for generic embedding or widely cached delivery (e.g., static shared assets or public CDNs).
@@ -383,7 +383,7 @@ Access-Control-Allow-Credentials: true
```
#### Clear-Site-Data (Logout)
-- **DO**: Use `Clear-Site-Data` on logout endpoints to ensure complete session termination.
+- **DO**: Send `Clear-Site-Data: "cookies", "storage", "cache"` on logout endpoints to ensure complete session termination; omitting any of these directives leaves active session cookies, Web Storage state, or cached authenticated pages behind.
```http
Clear-Site-Data: "cookies", "storage", "cache"
diff --git a/skills/modern-web-guidance/guides/ui-atoms/carousel-slide-effects.md b/skills/modern-web-guidance/guides/ui-atoms/carousel-slide-effects.md
index e0db76d..3c570bf 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/carousel-slide-effects.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/carousel-slide-effects.md
@@ -6,10 +6,11 @@ Carousel slide effects are a great way to add visual interest to a carousel. As
Here’s how to create carousel slide effects:
-1. **Create a scroller:** This element will act as the container for your carousel slides. In this example it uses `overflow-x: scroll` to allow horizontal scrolling.
+1. **Create a scroller:** This element will act as the container for your carousel slides. In this example it uses `overflow-x: scroll` to allow horizontal scrolling. When the slides contain no focusable elements, give the scroller `tabindex="0"` and an accessible name, because not every browser makes a scroll container keyboard-focusable. The name needs a role that supports one: a `<ul>` already has the `list` role, but a `<div>` needs one, for example `role="region"`.
```html
- <ul class="scroller">
+ <!-- The slides contain no focusable elements, so the scroller takes focus itself. The label is an example. -->
+ <ul class="scroller" tabindex="0" aria-label="Slides">
<li class="entry">1</li>
<li class="entry">2</li>
<li class="entry">3</li>
@@ -23,6 +24,8 @@ Here’s how to create carousel slide effects:
}
```
+ Optionally, add `scroll-snap-type: x mandatory` on the scroller and `scroll-snap-align: center` on the slides if you want items to snap cleanly to the center state when scrolling stops.
+
2. **Define the animation:** Create a CSS animation that defines the different states of your slides as they traverse the scrollport. You can define keyframes for any part of the animation. For example, you can define a state for when the slides are in the center of the scrollport by including a `50%` keyframe. In this example, the `scale` property makes the slides grow as they approach the center and shrink as they move away.
```css
@@ -55,6 +58,7 @@ Here’s how to create carousel slide effects:
This code animates the carousel items of a horizontal scroller on scroll using an **anonymous view-timeline**:
```css
+/* Scale values are examples; customize with performant properties such as transform, scale, or opacity */
@keyframes animate {
0% {
scale: 0.5;
@@ -69,17 +73,24 @@ This code animates the carousel items of a horizontal scroller on scroll using a
}
}
-.scroller > * {
- /* Applies the animation using an `auto` duration */
- animation: animate auto linear both;
- /* Sets the animation timeline to use an anonymous view progress timeline, tracking the element's progress through the scroller on the inline axis */
- animation-timeline: view(inline);
+/* Only runs the effect when the user has no reduced-motion preference */
+@media (prefers-reduced-motion: no-preference) {
+ /* Include (animation-range: entry) to exclude browsers with partial scroll-driven animation support */
+ @supports ((animation-timeline: view()) and (animation-range: entry)) {
+ .scroller > * {
+ /* Applies the animation using an `auto` duration */
+ animation: animate auto linear both;
+ /* Sets the animation timeline to use an anonymous view progress timeline, tracking the element's progress through the scroller on the inline axis */
+ animation-timeline: view(inline);
+ }
+ }
}
```
This code animates the carousel items of a horizontal scroller on scroll using a **named view-timeline**:
```css
+/* Scale values are examples; customize with performant properties such as transform, scale, or opacity */
@keyframes animate {
0% {
scale: 0.5;
@@ -94,14 +105,20 @@ This code animates the carousel items of a horizontal scroller on scroll using a
}
}
-/* This creates a named view-timeline on each carousel item. The timeline is used to drive the animation that is applied on the same element. */
-.scroller > * {
- /* Applies the animation using an `auto` duration */
- animation: animate auto linear both;
- /* Defines a named view progress timeline, tracking the element's progress through the scroller on the inline axis */
- view-timeline: --item inline;
- /* Sets the animation timeline to use the named view progress timeline defined above */
- animation-timeline: --item;
+/* Only runs the effect when the user has no reduced-motion preference */
+@media (prefers-reduced-motion: no-preference) {
+ /* Include (animation-range: entry) to exclude browsers with partial scroll-driven animation support */
+ @supports ((animation-timeline: view()) and (animation-range: entry)) {
+ /* This creates a named view-timeline on each carousel item. The timeline is used to drive the animation that is applied on the same element. */
+ .scroller > * {
+ /* Applies the animation using an `auto` duration */
+ animation: animate auto linear both;
+ /* Defines a named view progress timeline, tracking the element's progress through the scroller on the inline axis */
+ view-timeline: --item inline;
+ /* Sets the animation timeline to use the named view progress timeline defined above */
+ animation-timeline: --item;
+ }
+ }
}
```
@@ -117,7 +134,7 @@ When using scroll-driven animations, it's important to follow a few best practic
- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.
- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.
-Prefer a named `view-timeline` when multiple DOM elements need to animate based on the same timeline, or when you need to animate children of the element that has the `view-timeline` defined on it. If the element that you animate is also the element that defines the `view-timeline`, you can use an anonymous view-timeline using `view()`.
+Use an anonymous `view()` timeline by default when the animated element is the same element being tracked, so you do not have to name every individual timeline. Use a named `view-timeline` instead when multiple elements reuse a single timeline (avoiding duplicate timelines) or when reaching across the DOM (such as animating descendants or non-ancestors via `timeline-scope` when `view()` or `scroll(nearest)` does not suffice).
When using the `view()` function to create a scroll-driven animation:
@@ -131,9 +148,10 @@ When using the `view-timeline` property to create a scroll-driven animation:
## Browser support and fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.. Therefore, a fallback strategy is typically required.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Therefore, a fallback strategy is typically required.
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
@@ -141,11 +159,13 @@ In browsers with built-in support for scroll-driven animations, ALWAYS use the n
Note that not every effect can be recreated using the fallbacks approach.
-For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses the Web Animations API (`Element.animate()`) to create a paused animation for each item in the carousel. It then listens to the `scroll` event on the scroller and updates the `currentTime` of each animation based on the item's scroll progress within the scroller.
+For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses the Web Animations API (`Element.animate()`) to create a paused animation for each item in the carousel. It then listens to the `scroll` event on the scroller and updates the `currentTime` of each animation based on the item's scroll progress within the scroller. The `prefers-reduced-motion` media query in the CSS doesn't affect the animations the script creates, so the script checks the preference with `matchMedia()` and only runs when the user has no reduced-motion preference.
```js
// Fallback for browsers that don't support scroll-driven animations
-if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {
+// Like the CSS, it only runs when the user has no reduced-motion preference.
+if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)') &&
+ matchMedia('(prefers-reduced-motion: no-preference)').matches) {
const scroller = document.querySelector('.scroller');
const entries = document.querySelectorAll('.entry');
diff --git a/skills/modern-web-guidance/guides/ui-atoms/component-specific-light-dark-theme.md b/skills/modern-web-guidance/guides/ui-atoms/component-specific-light-dark-theme.md
index c547849..0b7c413 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/component-specific-light-dark-theme.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/component-specific-light-dark-theme.md
@@ -123,11 +123,15 @@ To adapt to the user's preferences in older browsers, use `prefers-color-scheme`
/* Define brand colors for each mode */
--color-brand-light: #0056b3;
--color-brand-dark: #00e5ff;
+ --color-brand-text-light: white;
+ --color-brand-text-dark: #001f24;
--color-brand: var(--color-brand-light);
+ --color-brand-text: var(--color-brand-text-light);
/* MANDATORY: Fallback for browsers without light-dark support */
@media (prefers-color-scheme: dark) {
--color-brand: var(--color-brand-dark);
+ --color-brand-text: var(--color-brand-text-dark);
}
/* Ignored in older browsers */
@@ -136,6 +140,7 @@ To adapt to the user's preferences in older browsers, use `prefers-color-scheme`
button.primary {
background-color: var(--color-brand);
+ color: var(--color-brand-text);
}
```
diff --git a/skills/modern-web-guidance/guides/ui-atoms/icons.md b/skills/modern-web-guidance/guides/ui-atoms/icons.md
index 5b00fba..19c3571 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/icons.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/icons.md
@@ -1,6 +1,5 @@
# Using and managing icons
-
## Choosing an Icon Technique
Icon storage and rendering are separate choices. For example, an SVG sprite can supply an icon to the CSS icon system or be referenced with `<use>`.
@@ -12,6 +11,8 @@ Icon storage and rendering are separate choices. For example, an SVG sprite can
To decide, ask two questions. Does CSS need to pick or swap the icon (component defaults, state changes, theming)? If yes, use the CSS icon system. Do you need to reach inside the icon beyond color? If yes and you control the icon source, design the symbol with custom properties and use `<use>`; if you do not control the source, inline the SVG. Third-party icon sets rarely expose custom properties, so `<use>` against them gives you color and little else.
+Whichever method you choose, make sure that all icons have a contrast of at least 3:1 against their backgrounds in light and dark color schemes. Refer to the Contrast section of `color` (via `npx -y modern-web-guidance@latest retrieve "color"`) for more details.
+
### Embedded or remote icons
Both the CSS icon system and `<use>` can take icons from a data URI, an individual file, or a sprite. Embedding (data URIs or inline SVG) avoids a request and renders with the first paint, but bloats CSS or HTML and cannot be cached separately, so it suits a small set of icons that appear on every page. Individual files are cached independently and loaded on demand, at the cost of one request each. A sprite is one cacheable request for the whole set, but downloads every icon whether used or not, and `<use>` can only reference a sprite from the same origin. Prefer embedding for a handful of core icons and a sprite or individual files for larger sets.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md b/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
index 0bcf055..313e66a 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
@@ -62,7 +62,7 @@ Like all container queries, `@container` can only style **descendants** of the c
```css
.tooltip-content::before {
/* Default "down" arrow for the 'top' position */
- content: "▼";
+ content: "▼" / "";
position: absolute;
inset-block-end: 0;
inset-inline-start: 1rem;
@@ -71,7 +71,7 @@ Like all container queries, `@container` can only style **descendants** of the c
/* Update to an "up" arrow when the 'flip-block' fallback (bottom) is active */
@container anchored(fallback: flip-block) {
.tooltip-content::before {
- content: "▲";
+ content: "▲" / "";
inset-block-start: 0;
inset-block-end: auto;
}
@@ -95,11 +95,34 @@ If you need to change properties on the container itself (like `margin` or `back
}
```
+## 5. Styling the inner container (optional)
+
+If the tooltip text is particularly long, use an inner container in the tooltip to ensure that, when visible, the tooltip will always fit between the trigger control and a side of the viewport. As an example, the following code will adhere to this when flipping the tooltip content on the block axis with `position-try: flip-block`.
+
+```html
+<button popovertarget="tooltip" id="anchor" aria-describedby="tooltip">anchor</button>
+<div id="tooltip" popover role="tooltip">
+ <div class="tooltip-content-inner"></div>
+</div>
+```
+
+```css
+.tooltip-content-inner {
+ max-block-size: calc(50dvb - var(--trigger-height));
+ overflow-block: auto;
+}
+```
+
## Best practices
- **Prefer logical fallbacks**: Use keywords like `flip-block` and `flip-inline` in `position-try-fallbacks` for simpler queries that handle RTL and different writing modes automatically.
- **Use pseudo-elements for arrows**: Tooltip arrows are purely decorative and are perfect candidates for `::before` or `::after`, which can be styled via anchored container queries without extra DOM.
+## Accessibility considerations
+
+Using these tooltips may result in controls being obscured when they receive focus, which would result in a fail against WCAG 2.4.11 Focus Not Obscured (Minimum) (Level AA), as focused items cannot be completely obscured. While there may not be generic guidance to completely mitigate against this issue, consider strategies that adjust the position of the tooltip or its presence.
+
+Keyboard navigation does not close a `popover=auto` tooltip, so ensure that tooltips do not obscure interactive elements as they receive focus via keyboard. If the tooltip is likely to obscure an interactive element when it receives focus, either change the position of the tooltip to prevent focus being obscured, or dismiss the tooltip if it is no longer relevant to the user.
## Fallback strategies
@@ -112,7 +135,7 @@ Positioning the arrow based on the applied fallback is a progressive enhancement
```css
@supports (container-type: anchored) {
.tooltip-content::before {
- content: "▼";
+ content: "▼" / "";
}
}
```
@@ -130,22 +153,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -153,6 +170,4 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
-
Browsers without support for the Popover API also do not support anchor positioning, so the tooltip will appear in the center of the screen.
\ No newline at end of file
diff --git a/skills/modern-web-guidance/guides/ui-atoms/pull-to-reveal.md b/skills/modern-web-guidance/guides/ui-atoms/pull-to-reveal.md
index da15021..ea90d13 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/pull-to-reveal.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/pull-to-reveal.md
@@ -51,6 +51,7 @@ To implement a pull-to-reveal pattern:
## Strategic Implementation & Best Practices
+- **MANDATORY:** give every pull to reveal action a visible button (or menu item) that performs the same action with a single click or the Enter key, as WCAG 2.5.1 Pointer Gestures requires for path-based gestures. Make each button at least 24×24 CSS pixels (WCAG 2.5.8 Target Size (Minimum)) and name it after the item it acts on.
- **DO** use `scroll-initial-target: nearest` when you want to draw the user's attention to a specific part of a scrollable area upon load and intentionally hide peripheral UI units like a search bar at the very top.
- **DO NOT** confuse this with accessibility focus. This property only moves the **visual** viewport; it does not move the keyboard focus. You must manually manage `element.focus()` if the target is intended to be the starting point for keyboard users.
- **DO NOT** use this if you need a smooth "scrolling" animation on load; this property is discrete and sets the position instantly during the layout phase.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
index 3392965..61fc1cf 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
@@ -10,6 +10,7 @@ The core of a responsive table is maintaining the relationship between data cell
2. **Sticky Context**: Apply `position: sticky` to both column headers and row headers. This ensures that no matter how far a user scrolls in any direction, they never lose the context of what the data represents.
3. **Adaptive Transformations**: Use `@container` queries instead of `@media` queries. This allows the table to adapt based on its own width (e.g., when placed in a sidebar or a narrow dashboard widget) rather than the entire viewport.
4. **Label Injection**: In the stacked layout, the `<thead>` is hidden, and accessible headers are injected into each cell using `::before` pseudo-elements and CSS variables.
+5. **Legible Cells**: Keep long cell text on one line instead of letting columns shrink below legibility. See `single-line-overflow` (via `npx -y modern-web-guidance@latest retrieve "single-line-overflow"`) for techniques for truncating it and revealing the full text on demand without UX friction.
## Implementation Steps
diff --git a/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md b/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md
index 18e405c..6e49e5d 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md
@@ -57,7 +57,7 @@ Use the `@container` rule with the `scroll-state` function. To check if the user
## Fallback strategies
Browser support for Container scroll-state queries: Limited availability.
-Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
+Supported by: Chrome 144 (Jan 2026) and Edge 144 (Jan 2026).
Unsupported in: Firefox and Safari.
### Basic Fallback
diff --git a/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md b/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md
index f88a0a5..c4e97fc 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md
@@ -45,8 +45,7 @@ Because of its location in the DOM, the `scroll()` function will track its neare
```html
<body>
- <!-- MANDATORY: Purely decorative visual scroll progress bars MUST set aria-hidden="true" to remove the empty element from the assistive technology reading tree -->
- <div id="progress" aria-hidden="true"></div>
+ <div id="progress"></div>
</body>
```
@@ -85,7 +84,7 @@ When using scroll-driven animations, it's important to follow a few best practic
- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports (animation-timeline: scroll())` to check for support and provide a fallback for browsers that don't support it.
- **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.
- If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.
-- **DO** remove purely decorative elements from assistive technology reading flows: Apply `aria-hidden="true"` to purely visual scroll indicators to ensure screen readers do not encounter empty, unnamed nodes.
+- **DO** keep purely decorative indicators out of assistive technology reading flows: An empty element styled only with CSS needs nothing extra. If the indicator contains text or images, apply `aria-hidden="true"` to it.
- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.
- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.
- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.
@@ -104,9 +103,8 @@ When using the `scroll-timeline` property to create a scroll-driven animation:
## Fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
diff --git a/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md b/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md
index e125c73..0807b7c 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md
@@ -2,125 +2,277 @@
## Overview
-Visual hints, like shadows or gradients, help users understand that they can scroll to see more content. This guide shows how to build these hints using CSS `container-scroll-state-queries`, which allows styling elements based on the scrollable state of their container without relying on JavaScript scroll listeners or observers.
+Scrollability hints show users that a region has more content in a given direction, and disappear at that end of the content. There are two kinds:
-## Implementation
+- **Shadows** are drawn over the edge of the scrollport, as if the content were tucked under it. Show them with scroll-state container queries on pseudo-elements of the scroller.
+- **Fades** make the content itself fade out at the edge. Draw them with a mask on the scroller, driven by a scroll-driven animation.
-### 1. Establish the Scroll Container
+Both need no scroll listeners and no extra elements in the markup.
-The scroll container must be declared as a scroll-state query container.
+## Choosing between a shadow and a fade
+
+Use a **fade** when:
+- The scroller scrolls horizontally through a row of items (tabs, chips, carousels). Items cut off by a fade read as "more of the same".
+- The background is not a solid color (gradients, images, translucent surfaces). A mask makes content transparent instead of painting over it, so it works on any background.
+- The scroller has no visible boundary. A fade needs no edge to tuck content under.
+
+Use a **shadow** when:
+- The content must stay legible right up to the edge (long text, tables, forms). A fade makes content near the edge hard to read.
+- The scroller is bounded by fixed chrome, such as a dialog's header and footer or a table's sticky header. The shadow makes the chrome look raised above the content.
+
+If neither applies, default to a shadow for vertical scrollers and a fade for horizontal ones.
+
+## Shadows
+
+### 1. Make the scroller a scroll-state container
```css
.scroller {
overflow-y: auto;
- /* Establish this element as a scroll-state query container */
container-type: scroll-state;
- position: relative;
}
```
-### 2. Style the Indicators
+### 2. Draw the shadows with `::before` and `::after`
-Place the indicator elements (like shadows, gradients, or arrows) inside the container and style them. By default, they should not be visible. When they are shown, they should not be interactive, by setting `pointer-events: none`.
+DO NOT add indicator elements to the markup. The scroller's own `::before` and `::after` are its first and last children, so `position: sticky` keeps them at the edges of the scrollport. Their negative margins cancel out their height, so they take no space.
```css
-.indicator-top, .indicator-bottom {
+.scroller::before,
+.scroller::after {
+ content: "";
+ display: block;
position: sticky;
- left: 0;
- right: 0;
- height: 20px;
+ /* Example value: how far the shadow reaches into the content */
+ block-size: .75rem;
+ /* Paint above positioned content */
+ z-index: 1;
+ /* Let clicks through to the content underneath */
+ pointer-events: none;
opacity: 0;
- transition: opacity 0.2s;
- pointer-events: none; /* Let clicks pass through */
+ transition: opacity .2s;
}
-.indicator-top {
- top: 0;
- background: linear-gradient(to bottom, rgba(0,0,0,0.2), transparent); /* Example: Shadow */
+/* Radial, so the shadow curves and tapers off at the sides. Keep it subtle: it should not compete with the content. */
+.scroller::before {
+ inset-block-start: 0;
+ margin-block-end: -.75rem;
+ background: radial-gradient(farthest-side at 50% 0, rgb(0 0 0 / .15), transparent);
}
-.indicator-bottom {
- bottom: 0;
- background: linear-gradient(to top, rgba(0,0,0,0.2), transparent); /* Example: Shadow */
+.scroller::after {
+ inset-block-end: 0;
+ margin-block-start: -.75rem;
+ background: radial-gradient(farthest-side at 50% 100%, rgb(0 0 0 / .15), transparent);
}
```
-### 3. Query the Scroll State
+The pseudo-elements take part in the scroller's layout even while hidden. This works best when the scroller uses block layout, or a single-column grid or flex column layout.
-Use the `@container` rule with the `scroll-state` function. Check if the container is scrollable up or down to show the respective indicator.
+### 3. Show each shadow when there is content beyond its edge
+
+Pseudo-elements can query their own originating element, so the scroller's `::before` and `::after` respond to its scroll state.
```css
-/* Show top indicator when the user can scroll up */
-@container scroll-state(scrollable: top) {
- .indicator-top {
+@container scroll-state(scrollable: block-start) {
+ .scroller::before {
opacity: 1;
}
}
-/* Show bottom indicator when the user can scroll down */
-@container scroll-state(scrollable: bottom) {
- .indicator-bottom {
+@container scroll-state(scrollable: block-end) {
+ .scroller::after {
opacity: 1;
}
}
```
+## Fades
+
+Fade the content with a mask on the scroller itself: an opaque layer minus a gradient band at each end. Masking only the bands keeps everything else visible, including a focus outline on the scroller, which a single gradient clipped to the border box would hide. Animate each band's size with a scroll-driven animation on the scroller's own scroll position: each fade grows from 0 as the user scrolls away from that end, and shrinks back to 0 as they reach the other end. When the content fits, the scroll timeline is inactive and there is no fade.
+
+```css
+@property --fade-start {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+@property --fade-end {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+.scroller {
+ overflow-x: auto;
+ /* Example value: how far each fade reaches */
+ --fade-size: 3rem;
+ /* Gradient directions and positions are physical, so flip them for right-to-left content */
+ --fade-dir: right;
+ --fade-start-pos: 0;
+ --fade-end-pos: 100%;
+ mask:
+ linear-gradient(black, black) no-clip subtract,
+ linear-gradient(to var(--fade-dir), black, transparent) var(--fade-start-pos) 0 / var(--fade-start) 100% no-repeat no-clip,
+ linear-gradient(to var(--fade-dir), transparent, black) var(--fade-end-pos) 0 / var(--fade-end) 100% no-repeat no-clip;
+ animation: reveal-fade-start linear both, hide-fade-end linear both;
+ animation-timeline: scroll(self inline);
+ /* Each fade animates over the first or last --fade-size of scrolling */
+ animation-range: 0 var(--fade-size), calc(100% - var(--fade-size)) 100%;
+
+ &:dir(rtl) {
+ --fade-dir: left;
+ --fade-start-pos: 100%;
+ --fade-end-pos: 0;
+ }
+}
+
+@keyframes reveal-fade-start {
+ to {
+ --fade-start: var(--fade-size);
+ }
+}
+
+@keyframes hide-fade-end {
+ from {
+ --fade-end: var(--fade-size);
+ }
+}
+```
+
+- MANDATORY: Register `--fade-start` and `--fade-end` with `@property`. Unregistered custom properties do not interpolate, so the fades would jump.
+- Set `scroll-padding-inline` (or `scroll-padding-block`) to the fade size if the scroller uses scroll snapping or contains focusable items, so snapped and focused items never stop inside a fade.
+- For vertical scrollers, use `to bottom`, put the bands at `0 0` and `0 100%` with sizes `100% var(--fade-start)` and `100% var(--fade-end)`, and use `scroll(self block)` and `overflow-y`.
+- For right-to-left content, flip `--fade-dir` and swap the band positions, as in the `:dir(rtl)` rule above. The scroll timeline follows the writing direction, but gradient directions and mask positions are physical.
+
+## Accessibility considerations
+
+Scrollability affordance hints are intended to supplement existing browser behaviour and help people be aware of larger scrollable regions. As a result of these hints being supplemental, and secondary to the primary hint (which would be the default scrollbar, or a sufficiently contrasting custom scrollbar), these scrollability affordance hints do not have to meet a specific contrast threshold. If the author wants to remove the scrollbar (which is not recommended for many usability reasons), then the scrollability affordance hint must have a contrast ratio of 3:1 against any immediately adjacent colours (to meet WCAG success criterion 1.4.11 Non-text Contrast), so that people are able to easily determine that scrolling is possible.
+
## Fallback strategies
+Hints are an enhancement: without them, the scroller still works. If your Baseline target does not support the features below, omitting the hints is acceptable when the scrollbar is visible. If the scrollbar is hidden, the hints are the only cue that the region scrolls, so you MUST use a fallback.
+
+### Fallbacks & browser support for scroll-state container queries
+
Browser support for Container scroll-state queries: Limited availability.
-Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
+Supported by: Chrome 144 (Jan 2026) and Edge 144 (Jan 2026).
Unsupported in: Firefox and Safari.
-### Basic Fallback
-If the feature is not supported, the indicators will remain invisible. Since these are hints and not critical for functionality, it is acceptable to omit them in unsupported browsers.
+Without scroll-state queries, the shadows stay hidden. Show them with a scroll-driven animation instead, which has broader support. The pseudo-elements are inside the scroller, so `scroll()` uses it as their timeline. Each shadow fades in over the first few pixels of scrolling away from its edge, instead of toggling.
+
+```css
+@supports not (container-type: scroll-state) {
+ .scroller::before,
+ .scroller::after {
+ animation: show-shadow linear both;
+ animation-timeline: scroll();
+ }
+
+ .scroller::before {
+ /* Example value: how much scrolling it takes to fully show the shadow */
+ animation-range: 0 2rem;
+ }
-### Advanced Fallback (Intersection Observer)
-If the hints are required, use an `IntersectionObserver` to toggle classes when sentinel elements at the top and bottom of the scroller move in and out of the scrollport.
+ .scroller::after {
+ animation-direction: reverse;
+ animation-range: calc(100% - 2rem) 100%;
+ }
+}
-```html
-<!-- Sentinel elements placed at the ends of the scroller -->
-<div class="sentinel-top"></div>
-<!-- Content goes here -->
-<div class="sentinel-bottom"></div>
+@keyframes show-shadow {
+ to {
+ opacity: 1;
+ }
+}
```
+When the content fits, the scroll timeline is inactive, so neither shadow shows. If your Baseline target does not support scroll-driven animations either, use one of the last-resort fallbacks below.
+
+### Fallbacks & browser support for scroll-driven animations
+
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Without scroll-driven animations, the fades are never shown, and neither are the shadows if scroll-state queries are also unsupported. Use one of these last-resort fallbacks.
+
+#### Shadows on a solid background: background attachment
+
+If the scroller has a solid background color, draw the shadows with backgrounds instead. This works in every browser and needs no JavaScript.
+Each shadow is a `scroll` background, which stays at the edge of the scrollport.
+Each shadow has a cover: a `local` background in the scroller's own color, which scrolls with the content.
+At either end of the content its cover sits on top of its shadow and hides it; once the user scrolls away from that end, the cover moves away and the shadow shows.
+
```css
-/* Marker styling to ensure it does not affect layout */
-.sentinel-top, .sentinel-bottom {
- height: 0;
- width: 0;
- visibility: hidden;
+@supports not ((container-type: scroll-state) or (animation-timeline: scroll())) {
+ .scroller {
+ background:
+ /* Covers: scroll with the content. Must use the scroller's own background color. */
+ linear-gradient(var(--surface) 30%, transparent) top / 100% 2.5rem no-repeat local,
+ linear-gradient(transparent, var(--surface) 70%) bottom / 100% 2.5rem no-repeat local,
+ /* Shadows: stay at the edges of the scrollport */
+ radial-gradient(farthest-side at 50% 0, rgb(0 0 0 / .15), transparent) top / 100% .75rem no-repeat,
+ radial-gradient(farthest-side at 50% 100%, rgb(0 0 0 / .15), transparent) bottom / 100% .75rem no-repeat,
+ var(--surface);
+ }
}
+```
-.scroller.scrolled-down .indicator-top {
- opacity: 1;
+The shadows paint behind the content, so content with its own opaque background hides them. In that case, use the `IntersectionObserver` fallback below.
+
+#### Fades, or shadows on any background: `IntersectionObserver`
+
+Use an `IntersectionObserver` to mark which edges have more content, and show the hints from those attributes. Observe the scroller's first and last children, with the scroller as the root and `threshold: 1`: a child that is not fully visible means there is more content beyond it.
+
+```js
+if (!CSS.supports('animation-timeline', 'scroll()')) {
+ for (const scroller of document.querySelectorAll('.scroller')) {
+ const [first, last] = [scroller.firstElementChild, scroller.lastElementChild];
+ // rootMargin: without it, sub-pixel widths can leave an edge child a fraction of a pixel short of fully visible
+ const observer = new IntersectionObserver(entries => {
+ for (const { target, intersectionRatio } of entries) {
+ scroller.classList.toggle(target === first ? 'more-start' : 'more-end', intersectionRatio < 1);
+ }
+ }, { root: scroller, threshold: 1, rootMargin: '1px' });
+
+ observer.observe(first);
+ observer.observe(last);
+ }
}
+```
-.scroller.can-scroll-down .indicator-bottom {
+```css
+/* Shadows */
+.scroller.more-start::before,
+.scroller.more-end::after {
opacity: 1;
}
+
+/* Fades */
+.scroller {
+ transition: --fade-start .2s, --fade-end .2s;
+
+ &.more-start {
+ --fade-start: var(--fade-size);
+ }
+
+ &.more-end {
+ --fade-end: var(--fade-size);
+ }
+}
```
-```javascript
-if (!CSS.supports('container-type', 'scroll-state')) {
- const topSentinel = document.querySelector('.sentinel-top');
- const bottomSentinel = document.querySelector('.sentinel-bottom');
- const scroller = document.querySelector('.scroller');
-
- const observer = new IntersectionObserver((entries) => {
- entries.forEach(entry => {
- if (entry.target === topSentinel) {
- // If top sentinel is not intersecting, we have scrolled down
- scroller.classList.toggle('scrolled-down', !entry.isIntersecting);
- }
- if (entry.target === bottomSentinel) {
- // If bottom sentinel is intersecting, we reached the bottom
- scroller.classList.toggle('can-scroll-down', !entry.isIntersecting);
- }
- });
- }, { root: scroller });
+If a single child can be larger than the scroller (e.g. one long article), it is never fully visible, so this would always show both hints. Observe sentinels instead: empty elements that the script adds at each end of the scroller. A sentinel that is out of view means there is more content beyond it.
- observer.observe(topSentinel);
- observer.observe(bottomSentinel);
+```js
+// Must be valid children of the scroller (e.g. <li aria-hidden="true"> in a list)
+const [start, end] = [document.createElement('div'), document.createElement('div')];
+for (const sentinel of [start, end]) {
+ // A zero-size sentinel at the very edge never counts as intersecting
+ sentinel.style.cssText = 'min-inline-size: 1px; min-block-size: 1px';
}
+scroller.prepend(start);
+scroller.append(end);
+// Observe them as above, with the default threshold, using !isIntersecting instead of intersectionRatio < 1
```
diff --git a/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md b/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md
index b975494..28878ee 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md
@@ -49,6 +49,8 @@ Here’s how to create a shrinking header on scroll:
}
```
+If using `position: sticky` on the header element, set `scroll-padding-top` to ensure that when elements receive focus, they aren't displayed under the sticky content. Set the `scroll-padding-top` value to be the height of the sticky element, which will ensure that when controls receive focus, they'll be consistently visible, positioned following the sticky content. This ensures adherence to WCAG 2.4.11 Focus Not Obscured, ensuring that focused controls aren't completely obscured. The value of `scroll-padding-top` can be animated on the same `scroll-timeline` used to shrink the header, keeping the value inline with the visual updates.
+
**Tip:** To prevent the content following the header from being obscured by it, add a `padding-top` to the `body` (or the main content container) that is equal to the initial height of the header.
**Tip:** To make sure the contents of the page scroll in sync with the shrinking header, set the `animation-range-end` to the difference between the start and end sizes. This ensures the animation completes precisely when the header reaches its final size. In this demo the header shrinks from `200px` to `50px`, so the `animation-range-end` is set to `150px`.
@@ -94,9 +96,8 @@ As for this use case specifically:
## Browser support and fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.. Therefore, a fallback strategy is typically required.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).. Therefore, a fallback strategy is typically required.
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
diff --git a/skills/modern-web-guidance/guides/ui-atoms/single-line-overflow.md b/skills/modern-web-guidance/guides/ui-atoms/single-line-overflow.md
new file mode 100644
index 0000000..07f04ce
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-atoms/single-line-overflow.md
@@ -0,0 +1,393 @@
+# Single-line text overflow
+
+Text that has to stay on one line (tab and chip labels, table cells, sidebar items, file names, media titles) is often longer than its space, especially with user content and translations.
+
+Keep the full text in the DOM and only adapt how it renders: the full text is the accessible name, and what find-in-page, copy, and search see.
+
+This guide does not cover use cases where wrapping is an acceptable option.
+
+There are two components to handling single-line text overflow:
+1. How to display the truncated text
+2. How can users find out what the full text is
+
+## How to display truncated text
+
+Truncation is visual only. Screen readers announce the full text, find-in-page matches it, and copying copies it. This is why the string must never be cut in script.
+
+### 1. Truncate with an ellipsis (at the end or middle)
+
+```css
+.label {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+```
+
+- Use `overflow: hidden`, not `clip`. Both render the ellipsis, but only `hidden` makes the element a scroll container, which the fade, the scroll reveal, and the CSS detection of truncation below depend on.
+- In flex/grid: Let the containing flex or grid item shrink. Items refuse to shrink below their content by default (`min-inline-size: auto`). When the truncated element is the item itself, `overflow: hidden` already allows it; when it is a descendant (such as a label inside a button), set `min-inline-size: 0` on the item.
+- In tables, set `table-layout: fixed` and an inline size on the table. With automatic layout, cells grow to fit their text instead of truncating it.
+- An element's own `overflow: hidden` does not clip its own focus outline, so buttons and links can truncate their text directly. Outlines are clipped by an ancestor that clips overflow, such as a scrolling row of items; give those items an inset outline (`outline-offset: -2px`).
+
+#### Keeping the end visible
+
+Wrap the part that may truncate, such as everything before the file extension or the last few characters, and leave the end as plain text after it. The split is in the markup (or done once in script when rendering), never by cutting characters out.
+
+```html
+<!-- No whitespace before the extension, or it renders as a space -->
+<span class="filename"><span>quarterly-report-final-v2</span>.pdf</span>
+```
+
+```css
+.filename {
+ display: flex;
+ white-space: nowrap;
+}
+
+/* The trailing text is an anonymous flex item, which never shrinks below its content */
+.filename > span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+```
+
+### 2. Fade out the end
+
+Use a mask that fades the end of the text. Only fade when the text overflows, or text that fits fades for no reason. An element with `overflow: hidden` is a scroll container, so its scroll timeline is only active when its content overflows. An animation on that timeline applies exactly when the text is truncated:
+
+```css
+/* --truncated is the flag the animation sets, registered so it does not inherit into nested elements.
+ --fade-size is the configured size, registered so it can transition. */
+@property --truncated {
+ syntax: "<integer>";
+ inherits: false;
+ initial-value: 0;
+}
+
+@property --fade-size {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+.label {
+ white-space: nowrap;
+ overflow: hidden;
+ /* Example value: how much of the text fades */
+ --fade-size: 2rem;
+ /* Gradient directions and positions are physical, so flip them for right-to-left text */
+ --fade-dir: right;
+ --fade-pos: 100%;
+ /* An opaque layer that is not clipped to the box, minus a band at the end.
+ Masking only the band keeps everything else visible, including a focus outline outside the box.
+ The band is --fade-size while truncated, 0 otherwise. */
+ mask:
+ linear-gradient(black, black) no-clip subtract,
+ linear-gradient(to var(--fade-dir), transparent, black) var(--fade-pos) 0 / calc(var(--truncated) * var(--fade-size)) 100% no-repeat no-clip;
+ /* Sets the flag only while the text overflows: with no overflow the timeline is inactive and the animation has no effect */
+ animation: truncated linear both;
+ animation-timeline: scroll(self inline);
+
+ &:dir(rtl) {
+ --fade-dir: left;
+ --fade-pos: 0;
+ }
+}
+
+@keyframes truncated {
+ from, to {
+ --truncated: 1;
+ }
+}
+```
+
+Keep the keyframes to the flag and derive the band from it. The reveal below transitions `--fade-size`, and a keyframe that set the band or the mask directly would not follow that transition in every browser.
+
+DO NOT use a single gradient as the mask. A mask is clipped to the border box by default, so it also hides the element's focus outline, which is outside the box.
+
+### 3. Replace with a predefined shorter version
+
+Put both versions in the markup and switch them with a container query on the cell or item. The short version is presentational: hide it from assistive technology and from selection, and hide the long version visually rather than with `display: none`, so the full text stays the accessible name and what copy and find-in-page see.
+
+```html
+<!-- The wrapper is the container: size containment has no effect on table cells themselves -->
+<td><div class="day"><span class="long">Saturday</span><span class="short" aria-hidden="true">Sat</span></div></td>
+```
+
+```css
+.day {
+ container-type: inline-size;
+}
+
+.short {
+ display: none;
+ user-select: none;
+}
+
+/* Example threshold: relative units resolve against the container's own font */
+@container (inline-size < 6em) {
+ /* Visually hidden, but still in the accessibility tree */
+ .long {
+ position: absolute;
+ inline-size: 1px;
+ block-size: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ }
+
+ .short {
+ display: inline;
+ }
+}
+```
+
+## Reveal full text on demand
+
+Reveal on `:hover` and `:focus-visible` of the interactive element, never on hover alone. Move the text only when `prefers-reduced-motion` is `no-preference`; otherwise leave the ellipsis.
+
+Hover and focus reveal nothing on touch. Give the full text another route: the selected item shows it untruncated (a selected tab is never shrunk), a row opens a detail view, or the text is also shown in full elsewhere.
+
+Choose by whether the element may grow:
+
+1. **Scroll the text inside its box** when nothing else may move: grids, tables, tab strips, dense lists. The element keeps its size.
+2. **Expand the element** when it may grow to its text, such as a chip or a tag with a `min-inline-size` and `max-inline-size`. Siblings shift to make room, so do not use it in grids or tables, where it breaks alignment.
+3. **Use a tooltip** when it would add information beyond the label, or when the full text can be exceedingly long (methods 1 and 2 are less tolerant of extreme variance)
+
+### 1. Scroll the text inside its box
+
+Move the text by the difference between the element's width and its own: a percentage margin resolves against the element, a percentage translate against the text itself. The element's own scroll timeline flags truncation in a custom property, and a style query on it limits the motion to truncated text, so text that fits stays put. The inner `span` is the only extra markup: it becomes the box that moves. The same class works on non-interactive elements such as list items, where hover still reveals.
+
+```html
+<a class="label" href="…"><span>Meeting notes from Tuesday afternoon</span></a>
+```
+
+```css
+.label {
+ display: block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ /* Active only while the text overflows */
+ animation: truncated linear both;
+ animation-timeline: scroll(self inline);
+}
+
+/* The same flag as the fade, registered there so it does not inherit */
+@keyframes truncated {
+ from, to {
+ --truncated: 1;
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ /* Outside the query: a container cannot query itself */
+ .label:is(:hover, :focus-visible) {
+ text-overflow: clip;
+ }
+
+ @container style(--truncated: 1) {
+ .label:is(:hover, :focus-visible) > span {
+ /* Needs its own box to be moved. It stays inline otherwise, so the ellipsis renders. */
+ display: inline-block;
+ /* Forward by the element's width, then back by the text's own width */
+ margin-inline-start: 100%;
+ /* 1px short, so the text still overflows and the timeline stays active */
+ translate: calc(1px - 100%);
+ /* Example values. Set only here: when the pointer leaves, the text snaps back behind the ellipsis */
+ transition: margin-inline-start 2s ease-in, translate 2s ease-in;
+ }
+
+ /* The overflow is on the left, so the text moves right */
+ .label:is(:hover, :focus-visible):dir(rtl) > span {
+ translate: calc(100% - 1px);
+ }
+ }
+}
+```
+
+The duration is fixed, so longer text scrolls faster. CSS cannot measure the text, so if a constant speed matters, set a `--scroll-width` custom property from script to the hidden width (`scrollWidth - clientWidth`, as a number) in the `ResizeObserver` from the detection section below, and derive the duration from it, for both the scroll and the fade:
+
+```css
+/* Example speed: 10ms per hidden pixel. Without script, assumes 200px. */
+transition-duration: calc(var(--scroll-width, 200) * 10ms);
+```
+
+Use a timing function that starts slowly and accelerates, such as `ease-in`: a pointer that only passes over barely moves the text, and the end, which is what the user is waiting for, arrives quickly.
+
+With a fade instead of an ellipsis, the text would scroll under the fade and its end would stay unreadable. Shrink the fade in step with the scroll, so it is gone when the end arrives:
+
+```css
+@media (prefers-reduced-motion: no-preference) {
+ .label:is(:hover, :focus-visible) {
+ --fade-size: 0px;
+ /* Same duration and easing as the scroll. Set only here, so the fade is back as soon as the text snaps back. */
+ transition: --fade-size 2s ease-in;
+ }
+}
+```
+
+### 2. Expand the element
+
+Let the element grow to its text, and transition the growth. Set `interpolate-size: allow-keywords` so the transition can interpolate to `max-content`.
+
+```css
+.chip {
+ /* Example values */
+ min-inline-size: 6rem;
+ max-inline-size: 12rem;
+ interpolate-size: allow-keywords;
+
+ & > span {
+ display: block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &:is(:hover, :focus-visible) {
+ max-inline-size: var(--expanded-max-inline-size, max-content);
+ }
+
+ @media (prefers-reduced-motion: no-preference) {
+ transition: max-inline-size .3s;
+ }
+}
+```
+
+### 3. Use a tooltip
+
+A tooltip is exposed as the element's description, while the label stays its name.
+If the tooltip only repeats the label, hide it from assistive technology (`aria-hidden="true"`), or screen readers announce the text twice.
+If it adds information, leave it exposed: name and description are announced as different things. If it also repeats the label, hide that part of the tooltip (`aria-hidden="true"` on it), so the description holds only the addition.
+DO NOT rely on `title` alone: it is unreachable from the keyboard and on touch.
+See `interest-triggered-tooltips` (via `npx -y modern-web-guidance@latest retrieve "interest-triggered-tooltips"`) for tooltips.
+
+## Detecting whether the text is truncated
+
+No property reports truncation. Derive it from overflow: the element is truncated when it can scroll toward its inline end. `text-overflow` only changes painting, so this holds with an ellipsis too.
+
+- **In CSS**, use a scroll-driven animation on the element's own inline scroll timeline, as in the fade above: it is active only while the text overflows. Declarations in the keyframes apply to the element itself. For descendants and pseudo-elements, set a custom property in the keyframes and read it with a style query. For example, to hint that hovering reveals more:
+
+ ```css
+ /* Registered so the flag does not inherit into nested truncated elements */
+ @property --truncated {
+ syntax: "<integer>";
+ inherits: false;
+ initial-value: 0;
+ }
+
+ .label {
+ animation: truncated linear both;
+ animation-timeline: scroll(self inline);
+ }
+
+ @keyframes truncated {
+ from, to {
+ --truncated: 1;
+ }
+ }
+
+ @container style(--truncated: 1) {
+ .label > span {
+ text-decoration: underline dotted;
+ }
+ }
+ ```
+
+ The element's `animation` carries the detection: add any other animation to that list, since declaring `animation` again replaces it.
+ DO NOT use a scroll-state query (`scrollable`) for this: the spec excludes `overflow: hidden` containers, so a browser that matches today may stop.
+
+- **In script**, when the result drives something CSS cannot (adding a tooltip, setting an attribute), compare `scrollWidth` to `clientWidth` in a `ResizeObserver`. Run the check again when the text changes: `ResizeObserver` reacts only to size changes.
+
+ ```js
+ const observer = new ResizeObserver(entries => {
+ for (const { target } of entries) {
+ target.classList.toggle('truncated', target.scrollWidth > target.clientWidth);
+ }
+ });
+ observer.observe(label);
+ ```
+
+## Fallback strategies
+
+### Fallbacks & browser support for scroll-driven animations
+
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Without scroll-driven animations the fade never shows, the hint never shows, and the scroll reveal never starts: the text is clipped with no indication. If your Baseline target does not support them, toggle a class from script: a `ResizeObserver` compares `scrollWidth` to `clientWidth`, and the class sets the same flag as the keyframes. Run the check again when the text changes: `ResizeObserver` reacts only to size changes.
+
+```js
+if (!CSS.supports('animation-timeline', 'scroll()')) {
+ const observer = new ResizeObserver(entries => {
+ for (const { target } of entries) {
+ target.classList.toggle('truncated', target.scrollWidth > target.clientWidth);
+ }
+ });
+
+ for (const label of document.querySelectorAll('.label')) {
+ observer.observe(label);
+ }
+}
+```
+
+```css
+/* Same as the keyframes */
+.label.truncated {
+ --truncated: 1;
+}
+```
+
+### Fallbacks & browser support for style queries
+
+Baseline status for Container style queries: Newly available. It's been Baseline since 2026-05-19.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 151 (May 2026), and Safari 18 (Sep 2024).
+
+Without style queries the fade still works, since it is on the element itself, but the hint and the scroll reveal never apply. Gate them on the class from the scroll-driven animations fallback above instead, and set that class without the `CSS.supports` guard: at-rules cannot be feature-detected.
+
+```css
+/* Same as the style queries */
+.label.truncated > span {
+ text-decoration: underline dotted;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .label.truncated:is(:hover, :focus-visible) > span {
+ display: inline-block;
+ margin-inline-start: 100%;
+ translate: calc(1px - 100%);
+ transition: margin-inline-start 2s ease-in, translate 2s ease-in;
+ }
+}
+```
+
+### Fallbacks & browser support for `interpolate-size`
+
+Browser support for interpolate-size: Limited availability.
+Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
+Unsupported in: Firefox and Safari.
+
+Without it, `max-content` cannot be interpolated and the element expands instantly. Transition to a length instead: one a little wider than the longest text. The growth stops as soon as the text fits, so a value far above it cuts the visible transition short.
+
+```css
+.chip {
+ @supports not (interpolate-size: allow-keywords) {
+ --expanded-max-inline-size: 20rem;
+ }
+}
+```
+
+### Fallbacks & browser support for container queries
+
+Baseline status for Container queries (size): Widely available. It's been Baseline since 2023-02-14.
+Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 110 (Feb 2023), and Safari 16 (Sep 2022).
+
+Container queries and their units are widely available. No fallback is needed.
+
+### Fallbacks & browser support for masks
+
+Baseline status for Masks: Widely available. It's been Baseline since 2023-12-07.
+Supported by: Chrome 120 (Dec 2023), Edge 120 (Dec 2023), Firefox 53 (Apr 2017), and Safari 15.4 (Mar 2022).
+
+Masks, including `mask-composite` and `mask-clip: no-clip`, are widely available. No fallback is needed.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md b/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md
index 438381e..1cadea8 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md
@@ -44,6 +44,15 @@ Set `container-type: scroll-state` on the `position: sticky` element, not on its
**Important:** The scroll state is queried by **descendants** of the scroll-state container. The styles in the `@container` query will not apply to the `.sticky-container` itself, but to its children (like `.sticky-header`). You cannot style the container element itself with its own scroll-state query.
+Add `scroll-padding-top` to the scrollport and set the value to be equal or greater than the sticky element's height. This approach should ensure that when controls receive focus, they'll be consistently visible below the sticky content, adhering to WCAG 2.4.11 Focus Not Obscured (Minimum), which requires that focused components are not fully obscured.
+
+```css
+html {
+ /* Accounts for the height of the header */
+ scroll-padding-top: var(--header-height);
+}
+```
+
### 3. Target the Stuck State
Use the `@container scroll-state(...)` query to apply styles when the header is stuck.
@@ -59,7 +68,7 @@ Use the `@container scroll-state(...)` query to apply styles when the header is
}
```
-**Tip:** You can also use logical properties like `stuck: inset-block-start` or `stuck: inset-inline-start` to better support internationalization (i18n) and right-to-left (RTL) layouts by querying flow-relative edges rather than physical ones.
+**Tip:** You can also use logical properties like `stuck: block-start` or `stuck: inline-start` to better support internationalization (i18n) and right-to-left (RTL) layouts by querying flow-relative edges rather than physical ones.
### Notes on Dimension Changes
@@ -79,7 +88,7 @@ DO NOT: Rely on `overflow-anchor: none` for elements stuck to the **bottom**. Sc
### Fallback strategies
Browser support for Container scroll-state queries: Limited availability.
-Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
+Supported by: Chrome 144 (Jan 2026) and Edge 144 (Jan 2026).
Unsupported in: Firefox and Safari.
Scroll state queries are a progressive enhancement. In browsers that do not support `container-type: scroll-state`, the header will still stick to the top (due to `position: sticky`), but it will not visually transform. For most use cases, this is the recommended approach.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md b/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
index e193524..8eb7ebf 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
@@ -78,22 +78,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -101,34 +95,84 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
+### Fallbacks & browser support for Anchor positioning
Browser support for Anchor positioning: Limited availability.
Supported by: Safari 27 (Sep 2026).
Unsupported in: Chrome, Edge, and Firefox.
-To support browsers without anchor positioning, you must set a reasonable position. By default popovers are centered in the middle of the screen, which may work for your use case.
+Without CSS Anchor Positioning, tethered elements such as `[popover]` overlays fall back to their default user-agent placement (centered in the viewport for popovers). Depending on whether spatial tethering is required for your use case, either conditionally load the polyfill or gate your positioning rules with `@supports`.
+
+#### Option 1: Polyfill (`@oddbird/css-anchor-positioning`)
+
+When the positioned element must stay spatially tethered to its trigger in unsupported browsers, conditionally load the `@oddbird/css-anchor-positioning` package.
-For some use cases, you may be able to use the `@oddbird/css-anchor-positioning` polyfill, which adds support for some anchor positioning use cases. It does not support implicit anchors, so you MUST add anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets.
+**MANDATORY:** Feature-detect support via `CSS.supports("anchor-name: --a")` (or `"anchorName" in CSSStyleDeclaration.prototype`), and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature-detect anchor positioning support before loading the polyfill.
+if (!CSS.supports("anchor-name: --a")) {
+ import("@oddbird/css-anchor-positioning");
+}
+```
+
+Without a bundler, import from a CDN inside a `<script type="module">`:
```html
<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->
<script type="module">
- if (!("anchorName" in document.documentElement.style)) {
- await import("https://unpkg.com/@oddbird/css-anchor-positioning");
+ if (!CSS.supports("anchor-name: --a")) {
+ import("https://unpkg.com/@oddbird/css-anchor-positioning");
}
</script>
```
+**Polyfill caveats:**
+- **No implicit anchors:** The polyfill does not support implicit anchor associations (such as those created by `popovertarget`, `commandfor`, `interestfor`, or `showPopover({ source })`). You **MUST** set a unique explicit `anchor-name` on each trigger and a matching `position-anchor` on the positioned element.
+- **No `position-area` with `position-try-fallbacks`:** `position-area` with `position-try-fallbacks` is not supported by the polyfill. When using the polyfill on elements needing fallbacks, position elements using `anchor()` functions on inset properties (`top`, `left`, `right`, `bottom`) with `inset: auto` instead of `position-area`.
+- **Do not wrap polyfilled rules in `@supports`:** Browsers without native anchor positioning evaluate `@supports (position-area: ...)` and `@supports (anchor-name: --a)` to `false` and discard the block before the polyfill can process it.
+
```css
-.panel {
- /* Mandatory: use explicit anchor name */
- position-anchor: --kebab-anchor;
- /* Mandatory: use insets rather than position-area for positioning */
- bottom: auto;
- right: auto;
+.trigger {
+ /* MANDATORY: Each trigger and positioned element pair must share a unique anchor name. */
+ anchor-name: --my-trigger;
+}
+
+[popover].anchored-overlay {
+ position-anchor: --my-trigger;
+ /* MANDATORY: Use anchor() on inset properties rather than position-area when using the polyfill on elements needing position-try-fallbacks. */
+ inset: auto;
top: anchor(bottom);
left: anchor(left);
margin: 0;
}
```
+
+#### Option 2: Progressive enhancement with `@supports` (no polyfill)
+
+If you do not ship the polyfill, **DO NOT** set `inset: auto` or `margin: 0` unconditionally on a `[popover]` element that relies on `position-area` or `anchor()`. In browsers without anchor positioning, `inset: auto` overrides the user-agent centering (`inset: 0; margin: auto`) while `position-area` is ignored, leaving the popover stranded at `(0, 0)` or overlapping its trigger.
+
+Instead, gate `inset: auto` and `margin: 0` inside `@supports` for the specific positioning feature used (for example, `@supports (position-area: block-end)` or `@supports (top: anchor(bottom))`) so unsupported browsers retain the default centered popover placement, or provide a matching `@supports not (...)` fallback layout (such as a fixed bottom sheet):
+
+```css
+@supports (position-area: block-end) {
+ [popover].anchored-overlay {
+ inset: auto;
+ margin: 0;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
+ }
+}
+
+@supports not (position-area: block-end) {
+ /* Optional: override default popover centering with a fixed bottom bar */
+ [popover].anchored-overlay {
+ position: fixed;
+ inset: auto 0 0 0;
+ width: auto;
+ margin: 0;
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md b/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md
index 796ef73..88a5fdd 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md
@@ -65,7 +65,7 @@ Because a 2D panning surface often lacks focusable child controls (for example,
- **Contain overscroll and prevent accidental navigations**: Add `overscroll-behavior: none` or `overscroll-behavior: contain` to the 2D scroll container so panning into a boundary does not chain to the parent page or trigger browser back/forward swipe navigation and pull-to-refresh gestures.
- **Nested one-dimensional panels keep railing automatically**: Because `scroll-axis-lock` does not inherit, a sidebar or inspector panel nested inside `.pan-viewport` retains the default `scroll-axis-lock: auto` behavior.
- **Keep `auto` on standard vertical feeds, articles, and one-dimensional lists**: Axis-locking prevents unintentional perpendicular drift in unidirectional content.
-- **Do not set `touch-action: none` unconditionally**: `touch-action` controls whether the browser handles touch gestures at all (and has no effect on trackpad or wheel input), so setting it disables native compositor touch scrolling. Only apply it inside `@supports not (scroll-axis-lock: none)` when implementing the JavaScript pointer fallback.
+- **Do not set `touch-action` unconditionally**: `touch-action` controls whether the browser handles touch gestures at all (and has no effect on trackpad or wheel input), so restricting it disables native compositor touch scrolling. Only apply it inside `@supports not (scroll-axis-lock: none)` when implementing the JavaScript pointer fallback, and use `touch-action: pinch-zoom` rather than `none`, so users can still pinch-zoom (WCAG 1.4.4 Resize Text).
- **Pan with `scrollLeft` / `scrollTop`, never CSS `transform`**: Translating the surface with `transform` stops the element from functioning as a scroll container—breaking native scrollbars, boundary clamping, keyboard Arrow-key scrolling, `scroll` events, `IntersectionObserver`, and scroll-driven animations.
## Fallback strategies
@@ -78,7 +78,7 @@ Choose between **progressive enhancement** and a **JavaScript fallback** based o
### Option 1: Progressive Enhancement (No JavaScript)
-Use progressive enhancement when preserving native compositor-thread touch scrolling, inertial fling momentum, and pinch-to-zoom is more important than eliminating axis-locking in unsupported browsers:
+Use progressive enhancement when preserving native compositor-thread touch scrolling and inertial fling momentum is more important than eliminating axis-locking in unsupported browsers:
- **Supporting browsers**: The browser prevents its axis-locking ("railing") heuristic from kicking in on the 2D scroll container during scroll gestures.
- **Unsupported browsers**: Browsers that do not recognize `scroll-axis-lock: none` safely ignore the declaration and keep their default `auto` 2D scrolling behavior—scrolling across both axes natively, while still railing gestures that begin predominantly along a single axis.
@@ -90,14 +90,15 @@ If unrestricted two-dimensional panning across all browsers is required, use `@s
Because `wheel` (`e.deltaX`, `e.deltaY`) and `pointermove` (`e.clientX`, `e.clientY`) expose raw, unlocked 2D deltas before the browser's scrolling engine applies axis-locking, you can apply those deltas directly to `scrollLeft` and `scrollTop`:
- **Why `scrollLeft`/`scrollTop` instead of CSS `transform`**: Updating `scrollLeft` and `scrollTop` keeps the element as a true scroll container. The browser automatically clamps scroll positions to `[0, scrollWidth - clientWidth]` and `[0, scrollHeight - clientHeight]`, native scrollbars stay synchronized, keyboard Arrow-key scrolling continues to work, and `scroll` events and `IntersectionObserver` fire normally.
-- **Trade-offs**: Intercepting `wheel` with `{ passive: false }` moves scrolling onto the main thread, and setting `touch-action: none` on touchscreens disables native inertial fling momentum after `pointerup` (as well as native pinch-to-zoom).
+- **Trade-offs**: Intercepting `wheel` with `{ passive: false }` moves scrolling onto the main thread, and setting `touch-action: pinch-zoom` on touchscreens hands panning to the script, which loses native inertial fling momentum after `pointerup`. `pinch-zoom` keeps pinch-to-zoom working, which `touch-action: none` would also disable.
```css
-/* Only disable native touch scrolling when scroll-axis-lock is unsupported
- and the JavaScript pointer fallback below is active. */
+/* Only disable native touch panning when scroll-axis-lock is unsupported
+ and the JavaScript pointer fallback below is active. pinch-zoom keeps
+ pinch-to-zoom working. */
@supports not (scroll-axis-lock: none) {
.pan-viewport {
- touch-action: none;
+ touch-action: pinch-zoom;
}
}
```
@@ -112,6 +113,7 @@ if (!CSS.supports('scroll-axis-lock', 'none')) {
viewport.addEventListener(
'wheel',
(e) => {
+ if (e.ctrlKey) return; // Ctrl+wheel and trackpad pinch zoom the page
e.preventDefault();
viewport.scrollLeft += e.deltaX;
viewport.scrollTop += e.deltaY;
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/anchor-positioning-tab-underline.md b/skills/modern-web-guidance/guides/ui-behaviors/anchor-positioning-tab-underline.md
index 31ef4b1..f3de5a9 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/anchor-positioning-tab-underline.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/anchor-positioning-tab-underline.md
@@ -1,6 +1,6 @@
# Anchor Positioning Tab Underline
-In a tab menu, you should provide visual hints to users about what page they are on. One option is by underlining the tab. With anchor positioning, you can create a smooth animation between the positions of the underline. This does not work when changing the active tab loads a new web page.
+In a tab menu, provide a visual indicator showing users which tab is active by underlining the active tab item. With anchor positioning, you can create a smooth animation between the positions of the underline as the active tab changes. This does not work when changing the active tab loads a new web page.
You can also use this effect to add an animated dot to indicate the active tab in a vertical tab bar.
@@ -44,13 +44,12 @@ ul::before {
}
```
-Add a height and other visual styles.
+Draw the underline with a border. DO NOT use a background or `box-shadow`: forced colors mode removes both, leaving no indicator.
```css
ul::before {
/* Apply your project's styles for the indicator */
- block-size: .25lh;
- background: red;
+ border-block-end: .25lh solid red;
}
```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/animate-element-entry-exit.md b/skills/modern-web-guidance/guides/ui-behaviors/animate-element-entry-exit.md
index 21fc98d..5095af1 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/animate-element-entry-exit.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/animate-element-entry-exit.md
@@ -18,11 +18,12 @@ To animate an element when toggling its visibility via an attribute (e.g., `hidd
display: block;
opacity: 1;
translate: 0;
- /* MANDATORY: Use transition-behavior: allow-discrete for display transition */
transition:
- display 0.4s,
- opacity 0.4s ease-out,
- translate 0.4s ease-out;
+ display,
+ opacity ease-out,
+ translate ease-out;
+ transition-duration: 0.4s;
+ /* Separate after transition so the shorthand doesn't reset it or fail in older browsers */
transition-behavior: allow-discrete;
}
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md b/skills/modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md
index 23b9859..1b024c2 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md
@@ -6,7 +6,7 @@ Elements that render in the "top layer" (like `<dialog>`, elements with the `pop
### 1. Enable Discrete Transitions
-To animate the `display` property, you must set `transition-behavior: allow-discrete`. This allows the element to remain visible during its exit transition. If using transition shorthands, be sure to place the `transition-behavior: allow-discrete` afterwards to prevent the shorthand from negating it.
+To animate the `display` property, you must set `transition-behavior: allow-discrete`. This allows the element to remain visible during its exit transition. If using the `transition` shorthand, place `transition-behavior: allow-discrete` afterward so the shorthand does not reset it.
### 2. The `overlay` Property
@@ -27,12 +27,19 @@ The `::backdrop` pseudo-element can be animated similarly by applying transition
dialog[open],
[popover]:popover-open {
opacity: 1;
- transform: scale(1);
/* 2. Define the starting state for entry (must come after open state) */
@starting-style {
opacity: 0;
- transform: scale(0.9);
+ }
+
+ /* Scale only for users who haven't asked for reduced motion (see 5) */
+ @media (prefers-reduced-motion: no-preference) {
+ transform: scale(1);
+
+ @starting-style {
+ transform: scale(0.9);
+ }
}
}
@@ -40,14 +47,17 @@ dialog[open],
dialog,
[popover] {
opacity: 0;
- transform: scale(0.9);
/* MANDATORY: transition display and overlay for top-layer elements */
transition-property: opacity, transform, display, overlay;
transition-duration: 0.3s;
transition-timing-function: ease-out;
- /* Applies to discrete properties like display and overlay */
- transition-behavior: allow-discrete; /* Note: be sure to write this after the shorthand */
+ /* Separate after transition so a shorthand doesn't reset it or fail in older browsers */
+ transition-behavior: allow-discrete;
+
+ @media (prefers-reduced-motion: no-preference) {
+ transform: scale(0.9);
+ }
}
/* 4. Animate the backdrop */
@@ -57,6 +67,7 @@ dialog::backdrop,
transition-property: background-color, display, overlay;
transition-duration: 0.3s;
transition-timing-function: ease-out;
+ /* Separate after transition so a shorthand doesn't reset it or fail in older browsers */
transition-behavior: allow-discrete;
}
@@ -69,29 +80,22 @@ dialog[open]::backdrop,
}
}
-/* 5. Respect user preference for reduced motion */
+/* 5. Respect user preference for reduced motion: the scale above only applies
+ with no-preference, so this only shortens the fade */
@media (prefers-reduced-motion: reduce) {
dialog,
[popover] {
- /* Disable movement and shorten duration for a simple fade */
- transform: none;
transition-duration: 0.1s;
}
-
- @starting-style {
- dialog[open],
- [popover]:popover-open {
- transform: none;
- }
- }
}
```
## Constraints & Accessibility
- **MANDATORY**: Include `overlay` in your `transition` list for any element moving into or out of the top layer.
-- **MANDATORY**: Use `allow-discrete` for the `display` property transition.
-- **MANDATORY**: Respect user preferences for reduced motion using `prefers-reduced-motion` by simplifying transitions (e.g., removing transforms and shortening duration).
+- **MANDATORY**: Use `transition-behavior: allow-discrete` when transitioning `display` and `overlay`.
+- **DO NOT**: Use `allow-discrete` in the `transition` shorthand — it will make older browsers ignore the entire `transition` declaration. Except in use cases where that is desirable, use a separate `transition-behavior: allow-discrete` declaration.
+- **MANDATORY**: Respect user preferences for reduced motion by applying transforms only inside `@media (prefers-reduced-motion: no-preference)` and shortening the transition duration inside `@media (prefers-reduced-motion: reduce)`, so users who prefer reduced motion get a short fade.
- **DO**: Place the `@starting-style` block inside or after the "open" state selector to ensure proper cascading.
- **DO NOT**: Use `@starting-style` for exit animations; exit animations are defined by the transition to the base (closed) state.
@@ -148,11 +152,17 @@ Exit animations require both `overlay` and discrete `display` transition support
```css
:is(dialog[open], [popover]:popover-open):where(:not([data-closing])) {
opacity: 1;
- transform: scale(1);
@starting-style {
opacity: 0;
- transform: scale(0.9);
+ }
+
+ @media (prefers-reduced-motion: no-preference) {
+ transform: scale(1);
+
+ @starting-style {
+ transform: scale(0.9);
+ }
}
&::backdrop {
@@ -214,27 +224,19 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
-
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
display: block;
}
```
-
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/carousel-snap-highlights.md b/skills/modern-web-guidance/guides/ui-behaviors/carousel-snap-highlights.md
index e7c422d..f90c766 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/carousel-snap-highlights.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/carousel-snap-highlights.md
@@ -83,23 +83,32 @@ Only show the effect for users not requesting reduced motion. Disable completely
The `snapped` descriptor can query specific axes: `x`, `y`, `inline`, `block`, or `both`.
-
### Accessibility
-**AVOID**: using `scroll-state` with interactive elements.
+* **DON'T** use `scroll-state` as a way to have people select an option.
+* **AVOID**: using `scroll-state` with interactive elements.
-Visual highlights for snapped items can improve the UX, but the snapped item is not exposed to the accessibility tree. The visual theme applied to a snapped item should not convey that the element is active or focused, and a keyboard focus ring should be highly visible and distinct from the `snapped` highlight. If the snapped item is interactive, you must use other standard accessibility practices to make it accessible.
+Visual highlights for snapped items can improve the UX, but the snapped item is not exposed to the accessibility tree. Therefore, snapping an item must not be used as a way of selecting content, and as a result, the visual theme applied to a snapped item must not convey that the element is active or focused. A sufficiently contrasting keyboard focus ring (with a contrast ratio of at least 3:1 against adjacent colors) should be distinct from the `snapped` highlight. If the snapped item is interactive, you must use other standard accessibility practices to make it accessible.
-Snapping occurs due to scrolling, which does not move keyboard focus. However, keyboard focus may cause the scroll container to move, causing a change in the snapped item, which may or may not be the focused item. This will likely be a source of confusion for users and is discouraged.
+Snapping occurs due to scrolling, which does not move keyboard focus. However, if focus moves to an element inside the scroll container, this may cause the scroll container to move, causing a change in the snapped item, which may or may not be the focused item. This will likely be a source of confusion for users and is why including interactive elements in the container is discouraged.
> [!NOTE]
-> Detailed accessibility requirements for carousels (such as ARIA roles, slide attributes, and complex keyboard patterns) have been intentionally omitted from this guide. Carousel accessibility is highly nuanced and context-dependent; refer to established accessibility standards and perform thorough user testing for production environments.
+> This pattern does not represent a traditional carousel component in which slides typically automatically change, in a way that doesn't allow people to pause or stop the transition, or accurately communicate the visible information to people using screen readers. If the intended use case is a carousel that only presents a single slide at any time, then do not use this technique, as it lacks the accessibility information required for such a component. Instead, opt for a tab-like implementation, ensuring that the carousel can be operated using a keyboard alone, that the carousel can be paused or stopped, and that the semantic information including the name, role, and state, is accurately conveyed to people using screen readers. Making carousel components accessible to everyone is highly nuanced and context-dependent; be sure to refer to established accessibility standards and perform thorough user testing for production environments.
+
+For content in the container that is not currently highlighted, ensure that this content is not inadvertently made difficult to perceive. For example, don't make the non-highlighted items in a gallery greyscale with a low opacity, only receiving adequate contrast once scroll snapped and highlighted. The content must always have sufficient contrast, in order for it to be perceivable, and to allow people to understand that there is more content that they can navigate to.
+
+Finally, to ensure consistent operability across different browsers and assistive technology combinations, ensure that the scrollable container can receive focus (by applying `tabindex="0"`), and has an accessible name that describes the content, along with an appropriate role (such as `role="region"`).
+```html
+<div class="carousel-snap" role="region" aria-label="Highlights" tabindex="0">
+ …
+</div>
+```
## Fallback strategies
Browser support for Container scroll-state queries: Limited availability.
-Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
+Supported by: Chrome 144 (Jan 2026) and Edge 144 (Jan 2026).
Unsupported in: Firefox and Safari.
For browsers that do not support scroll-state queries, you should provide a functional base experience where all items are legible, even without the "active" highlight.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/custom-button-actions.md b/skills/modern-web-guidance/guides/ui-behaviors/custom-button-actions.md
index f9c7b5e..05837c1 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/custom-button-actions.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/custom-button-actions.md
@@ -98,6 +98,8 @@ For the best performance, you should only load the polyfill if the browser doesn
**NOTE:** This polyfill does not manage ARIA states (like `aria-pressed` or `aria-expanded`) for custom commands. You must manually synchronize these states in your event listener to ensure your site is accessible.
+#### Conditionally load the Invoker Commands polyfill
+
```javascript
// 1. Conditionally load the polyfill
const hasNativeSupport = 'commandForElement' in HTMLButtonElement.prototype;
@@ -112,7 +114,11 @@ if (!hasNativeSupport) {
}
})();
}
+```
+
+#### Manually manage ARIA states in your listener
+```javascript
// 2. Manually manage ARIA states in your listener
document.getElementById('action-target').addEventListener('command', (event) => {
const command = event.command;
@@ -149,7 +155,6 @@ if (!globalThis.CommandEvent) {
this.command = command;
}
}
-}
// 3. The fallback: Dispatch events manually if native support is missing
document.addEventListener('click', (event) => {
@@ -166,6 +171,7 @@ if (!globalThis.CommandEvent) {
}));
}
});
+}
// 4. **Mandatory:** Register the unified listener directly on the target element
document.getElementById('action-target').addEventListener('command', (event) => {
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md b/skills/modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md
index 0218fc0..b955f74 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/declarative-dialog-popover-control.md
@@ -23,6 +23,8 @@ Popovers can be toggled open and closed using a single button.
If you need to control opening and closing with separate buttons, you can use the `show-popover` and `hide-popover` commands.
+**IMPORTANT:** Do NOT combine `popovertarget` and `commandfor` on the same `<button>`, for the same popover. This will double-toggle it, breaking functionality.
+
```html
<!-- MANDATORY: Use 'show-popover' to explicitly open the popover. It will not close the popover if clicked again. -->
<button commandfor="my-explicit-popover" command="show-popover">
@@ -39,6 +41,8 @@ If you need to control opening and closing with separate buttons, you can use th
</div>
```
+Hiding a popover, using a button inside the popover itself, will result in a loss of focus as the button will be hidden and won't retain focus. In this situation, provide additional scripting to return focus to the trigger/show control, so that people can continue to navigate from where they were previously.
+
## Implementing Declarative Modal Dialogs
Unlike popovers, modal dialogs typically use separate buttons for opening and closing. Use the `show-modal` command specifically when you need to open a dialog as a modal.
@@ -99,34 +103,7 @@ For projects without a bundler, dynamically import the polyfill directly from a
**Invokers Polyfill Limitations**
MANDATORY: This polyfill does not handle the ARIA states (e.g., `aria-expanded`) of the command button the way native browsers do. You are strongly encouraged to handle these states yourself to ensure your site is fully accessible.
-Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
-Supported by: Chrome 135 (Apr 2025), Edge 135 (Apr 2025), Firefox 144 (Oct 2025), and Safari 26.2 (Dec 2025).
-
-If the Invoker Commands API is not supported, the `command` event will not fire. For full support across all modern browsers, it is recommended to use the invokers-polyfill from https://github.com/keithamus/invokers-polyfill via `npm install` or CDN.
-
-This polyfill fully supports custom actions (starting with `--`) and dispatches the `command` event exactly like the native API.
-
-### Dynamic Import (Performance Optimization)
-
-For the best performance, you should only load the polyfill if the browser doesn't support the API natively. This saves bandwidth and reduces script execution time for users on modern browsers.
-
-**NOTE:** This polyfill does not manage ARIA states (like `aria-pressed` or `aria-expanded`) for custom commands. You must manually synchronize these states in your event listener to ensure your site is accessible.
-
```javascript
-// 1. Conditionally load the polyfill
-const hasNativeSupport = 'commandForElement' in HTMLButtonElement.prototype;
-
-if (!hasNativeSupport) {
- // Wrap in an async IIFE to avoid top-level await issues in older browsers
- (async () => {
- try {
- await import('https://esm.run/invokers-polyfill');
- } catch (err) {
- console.error('Error loading fallback:', err);
- }
- })();
-}
-
// 2. Manually manage ARIA states in your listener
document.getElementById('action-target').addEventListener('command', (event) => {
const command = event.command;
@@ -142,57 +119,6 @@ document.getElementById('action-target').addEventListener('command', (event) =>
});
```
-### Manual fallback (Traditional pattern)
-
-If you prefer not to use a polyfill, you can use a combination of **event delegation** to dispatch events and a **command registry** to handle the actions. This is a common architectural pattern in traditional JavaScript development that remains highly efficient and scalable.
-
-```javascript
-// 1. **Optional:** Define a registry of requested actions for cleaner logic
-const commandRegistry = {
- '--spin': (target) => target.classList.toggle('is-spun'),
- '--grow': (target) => target.classList.toggle('is-grown'),
- '--reset': (target) => target.classList.remove('is-spun', 'is-grown'),
-};
-
-// 2. If CommandEvent doesn't exist, we assume no native support and provide the fallback
-if (!globalThis.CommandEvent) {
- globalThis.CommandEvent = class CommandEvent extends Event {
- constructor(type, { source, command, ...options } = {}) {
- super(type, options);
- this.source = source;
- this.command = command;
- }
- }
-}
-
-// 3. The fallback: Dispatch events manually if native support is missing
- document.addEventListener('click', (event) => {
- const button = event.composedPath().find((el) => el.matches?.("button[commandfor]"));
- if (!button) return;
-
- const target = document.getElementById(button.getAttribute('commandfor'));
- const command = button.getAttribute('command');
-
- if (target && command) {
- target.dispatchEvent(new CommandEvent('command', {
- command,
- source: button,
- }));
- }
- });
-
-// 4. **Mandatory:** Register the unified listener directly on the target element
-document.getElementById('action-target').addEventListener('command', (event) => {
- const command = event.command;
- const target = event.target;
- const action = commandRegistry[command];
-
- if (action) {
- action(target);
- }
- });
-```
-
### Fallbacks & browser support for Popover
Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
@@ -206,27 +132,19 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
-
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
display: block;
}
```
-
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/directional-navigation-transitions.md b/skills/modern-web-guidance/guides/ui-behaviors/directional-navigation-transitions.md
index 180255c..1969eb0 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/directional-navigation-transitions.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/directional-navigation-transitions.md
@@ -39,7 +39,7 @@ Define sliding animations to and from each direction. For best performance, anim
### Set up shared animation settings
-Use the `::view-transition-group(root)` selector to apply animation settings that are shared across all transitions.
+Use the `::view-transition-group(root)` selector to apply animation settings that are shared across all transitions. The transition group must use a non-linear timing function (such as an `ease` keyword or `cubic-bezier()`) rather than `linear`, which makes directional slide transitions feel mechanical and abrupt.
```css
::view-transition-group(root){
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/drag-and-drop.md b/skills/modern-web-guidance/guides/ui-behaviors/drag-and-drop.md
new file mode 100644
index 0000000..31b7098
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/drag-and-drop.md
@@ -0,0 +1,106 @@
+# Rearrange Items with Drag and Drop
+
+Add reordering to an existing list or row, vertical or horizontal. Reorder the real children in the DOM (not via CSS `order` or `flex-direction: *-reverse`) so visual, keyboard, and reading order stay aligned. For free-form 2D repositioning of a floating element such as a dialog or toolbar, see `drag` (via `npx -y modern-web-guidance@latest retrieve "drag"`). This guide covers one axis at a time; it does not cover reordering a grid or wrapped layout, or moving items between lists.
+
+When items contain interactive controls or selectable text, provide a dedicated drag handle rather than making the entire item draggable. Then set up the pointer drag:
+
+- Start pointer drags only for the primary button, and record the initial pointer offset.
+- Apply `cursor: grab`/`grabbing`, `touch-action: none`, and `user-select: none` to the handle so item text remains selectable and page scrolling works outside the handle. Scope `touch-action: none` to the handle only: it disables touch scrolling over the element, which is acceptable on a small dedicated handle (the rest of the item and the page still scroll) but would trap scrolling if applied to the whole item or list.
+- Because the pointer leaves the handle as soon as the drag moves, `:active` on the handle isn't enough to keep the grabbing cursor. Toggle a class on the root element for the length of the drag (removed in the drag-end cleanup) and set `cursor: grabbing` on it and its descendants.
+
+## Keep movement active while reordering
+
+Keep the drag active and find the destination reliably:
+
+- **Capture the pointer.** Keep the drag active after the pointer leaves the handle with `handle.setPointerCapture(event.pointerId)` on `pointerdown`, and clean up on `lostpointercapture` unless capture was deliberately re-established after a `before()` move (see the `moveBefore()` section).
+- **Follow one pointer.** Remember the `pointerId` that started the drag and ignore `pointerdown`, `pointermove`, `pointerup`, and `pointercancel` from any other pointer, so an accidental second touch (such as the thumb holding a phone) can't start a competing drag or end the active one.
+- **Let `Escape` cancel.** On `Escape`, record the item's current rect, clear its drag `translate` without moving it in the DOM, scroll the item's slot back into view if the container scrolled, animate it back from the recorded rect, and announce the cancellation.
+- **Find the destination from layout, not `event.target`.** Pointer capture redirects `pointermove` `event.target` to the capturing handle. Clamp the pointer to the container's bounds on the list's axis and compare it with each sibling's layout midpoint. For a vertical list use `offsetTop + offsetHeight / 2`, with `position: relative` on the container and its `clientTop` and `scrollTop` accounted for. The drop spot is before the first sibling whose midpoint is below the pointer, or at the end if none is. For a horizontal row use `offsetLeft + offsetWidth / 2` with `clientLeft` and `scrollLeft`: `offsetLeft` and `scrollLeft` share one coordinate space in both reading directions (`scrollLeft` is negative once a right-to-left row is scrolled), so the same sum works for either. In a right-to-left row the DOM order runs right to left, so insert before the first sibling whose midpoint the pointer is already past, rather than the first one it has not reached.
+- **Why layout midpoints.** Layout positions ignore in-flight `translate` animations and padding gaps, so a pointer past either edge reliably resolves to the first or last place. `document.elementFromPoint()` hit-tests painted positions and can miss items while siblings are animating. Use `document.elementFromPoint(event.clientX, event.clientY)` only when the destination is one of several containers (such as board columns).
+
+Don't reorder while the pointer moves: shifting siblings feel jittery. Keep the source item in its slot and show a drop marker. This is the default for a single-axis list:
+
+- **Render a marker, not a shift.** Set `data-drop` on the list during a drag and draw the marker with its `::before` (ring) and `::after` (line), both `position: fixed; pointer-events: none`. Don't append an element to `<body>`.
+- **Place it in the gap.** On every drop-spot update and scroll step, set `--drop-x`, `--drop-y`, `--drop-w` and `--drop-h` from the neighbors' `getBoundingClientRect()`, centering the line in the gap between the previous and next item (on the inline axis, flipped in right-to-left, for rows). Don't use CSS anchor positioning (it drifts while autoscrolling), and keep `transform`, `filter` and `contain` off the list and its ancestors.
+- **Skip no-op drops.** Show no marker when the drop spot is the item's own slot. Remove `data-drop` and the custom properties when the drag ends.
+- **Make it themeable.** Drive color, line size, ring size, gap, lifted-item opacity and shadow from custom properties (such as `--drop-marker-color`) with defaults that suit the host design system, and use `Highlight` under `forced-colors: active`.
+- **Move once on release.** On `pointerup`, if the drop spot differs from the item's current next sibling, move the existing item node atomically with `container.moveBefore(item, referenceNode)` rather than recreating it, so internal state (such as focused controls, input values, scroll position, media, or custom element instances) and active pointer capture are preserved. Keyboard moves use the same call on each step. Then animate the move:
+
+- **Animate every move.** Items should visibly travel instead of jumping, including the move on release and keyboard moves. Record each sibling's `getBoundingClientRect()` before the move, then afterwards animate the `translate` property from the old offset (on both axes, correcting for any scroll that happened) to `0 0` (FLIP).
+- **Animate the release.** When the pointer is released, animate the item from its released position to its final rect (FLIP), measured after finishing the item's in-flight animations (`item.getAnimations().forEach((animation) => animation.finish())`) because otherwise the rect includes the animation's offset. Keep it raised until the animation finishes.
+- **Respect reduced motion.** Skip the animations under `prefers-reduced-motion: reduce`.
+- **Lift the real item; don't clone it.** Keep the dragged item in the DOM and in its layout slot, and follow the pointer with a `translate` (add the list's scroll change since the grab so auto-scroll keeps it under the pointer). Give it `position: relative`, a raised `z-index`, a slight `scale`, a shadow, and `pointer-events: none`. Its empty slot shows where it was picked up from. A clone duplicates IDs, loses state, breaks descendant selectors, framework bindings, and `idref`s, and ends up as invalid markup when appended outside the list. On release, animate the item from its dragged position to its new spot.
+- **Handle a quick re-grab.** Don't clear the item's drag state from a finished animation's callback if a new drag of that item has already started.
+
+## Scroll while dragging
+
+If the items live in a scrollable container, scroll it while the pointer is near or beyond its start or end edge on the list's axis (top and bottom, or left and right for a row, using `scrollTop` or `scrollLeft`), so off-screen items stay reachable (especially on small viewports). Run a `requestAnimationFrame` loop for the duration of the drag that scales scroll speed with how far the pointer is into an edge zone (the dragged item's size on the list axis, capped at a third of the container's size so the two zones never overlap), continuing to increase beyond the edge up to a cap, and uses frame time rather than a fixed step. After each scroll change, re-run drop-spot detection with the last pointer position, clamped into the container's bounds, because the pointer hasn't moved. Avoid `scroll-behavior: smooth` on that container. Give it space on every side so focus rings and elevation shadows aren't clipped: the space must cover the focus ring's outline width and offset plus the grabbed item's scale growth (about 1rem for a 3px outline, 2px offset, and `scale(1.02)`), and `overflow-y: auto` also clips on the x axis. Put the end space (bottom, or inline-end for a row) on the last item's margin rather than the container's padding, because some engines omit a grid or flex container's end padding from its scrollable overflow. Cancel the loop when the drag ends.
+
+## Support keyboard reordering
+
+Provide a keyboard-accessible alternative to pointer reordering. Choose an interaction that fits how frequently users reorder items and how easily they need to discover it:
+
+- **Visible movement controls or an actions menu**: Best default for discoverability and screen-reader compatibility, because activating standard buttons works in screen-reader browse modes without intercepting arrow keys. Use an actions menu when persistent inline buttons add too much visual clutter.
+- **Direct arrow keys (or modifier + arrow keys, such as `Alt` + arrow keys) on a focusable handle or item**: Suits frequent reordering with minimal UI chrome. Give the handle an accessible name that identifies both the item and the reorder action, and note that screen-reader browse modes may intercept bare arrow keys on a `<button>` handle unless paired with explicit movement controls or modifier keys.
+- **Grab–move–drop mode (`Space` or `Enter` to pick up, arrow keys to move along the list's axis, `Space` or `Enter` to drop, `Escape` to cancel)**: Arrow keys do nothing until the item is grabbed, which keeps them from conflicting with screen-reader navigation. Toggle `aria-pressed` on the handle, announce the grabbed state and available keys on pickup, restore the item to its original DOM position on `Escape`, and drop when the handle itself loses focus (not only when focus leaves the whole list, since the next stop is often another control in the same item), ignoring any blur caused by the move itself.
+
+The keys follow the list's axis: `ArrowUp` and `ArrowDown` for a vertical list, `ArrowLeft` and `ArrowRight` for a row. Arrow keys follow the visual direction, so in a right-to-left row `ArrowLeft` moves the item later in the DOM and `ArrowRight` earlier. Ignore the other axis's keys, use matching direction labels and icons on any move buttons, and name the direction in the announcement.
+
+For any approach, announce the item and its new position in a polite live region, resetting its text and delaying the update briefly (see the `moveBefore()` fallback below) so moves that refocus the handle are still announced. Announce only when the position actually changed (not for a click or a drop in place), while still announcing a cancellation. Show focus and the grabbed state on the item being moved, not just the handle:
+
+- **Keep the item in view.** After each keyboard move (including `Escape` restoring the original position) and each pointer drop, call `item.scrollIntoView({ block: 'nearest', inline: 'nearest' })` after the move but before starting the animation, because an in-flight `translate` skews the position it scrolls to. Restore focus afterwards with `focus({ preventScroll: true })` so the browser doesn't scroll again, and give items a `scroll-margin` matching the space around them in the container.
+- **Reveal the whole item on keyboard focus.** The browser otherwise scrolls only the focused handle into view and leaves the rest of the item and its focus ring clipped. When keyboard focus enters an item (for example with `Tab`), scroll the item the same way (`block` and `inline` both `'nearest'`) from a `focusin` handler that checks `:focus-visible` and skips items with running animations.
+- **Draw the focus ring on the item** with `.item:has(.handle:focus-visible)`. For grab–move–drop handles, show a visible key hint on the focused item (an `aria-hidden="true"` element in the item reading "Space to reorder", switching to "Arrows to move · Space to drop · Esc to cancel" while grabbed—keep instructional text in the DOM rather than CSS `content` so it stays translatable), and fade the handle slightly at rest so reordering reads as available. Also apply the handle's hover style on `:focus-visible` (`.handle:is(:hover, :focus-visible)`) so sighted keyboard users see the handle is activatable; use a fill rather than an outline so it doesn't read as a second focus ring, and give the grabbed (`aria-pressed`) state its own pressed look.
+- **Elevate the grabbed item** with full opacity, a slight `scale()`, and `box-shadow`. Avoid rotation, especially when movement is on one axis.
+- **Keep the layout shrinkable.** Make each row's flexible column shrinkable (`minmax(0, 1fr)` with form controls at `width: 100%`) so the movement controls stay visible on narrow viewports without horizontal scrolling.
+
+### Align reading order with visual layout
+
+Keep the DOM and keyboard focus order understandable in relation to the visual layout. If reordering is provided through separate controls, ensure the item's context is available before or alongside those controls. If the drag handle is focusable, give it an accessible name that identifies the item and its reordering function. Position controls to suit the layout and writing direction without making the resulting reading or focus order confusing.
+
+For complex layouts where visual and DOM order cannot naturally align, use the **`reading-flow`** CSS property inside grid/flex containers to instruct the browser's tab order to follow visual coordinates rather than DOM source order:
+```css
+.task {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto; /* minmax(0, ...) lets the middle column shrink at narrow widths */
+ reading-flow: grid-rows; /* Follows visual layout and tab order by row */
+}
+```
+
+### Disable boundaries and safeguard focus
+Keep moves within valid destinations. If items can move between containers, make those destinations available to keyboard users too. At the boundary of a container, prevent further movement only when there is no valid destination in that direction.
+
+After moving an item, keep focus on its handle. If the implementation uses separate movement buttons instead, keep focus on the activated button or shift it to the alternative movement control on the same item when the activated control becomes disabled.
+
+## Decide on fallback behavior
+
+When reordering is supplementary, keep the collection readable and usable in its default DOM order without JavaScript. If the order represents user-controlled data or directly affects behavior—for example, task priority, playlist order, or workflow sequence—treat reordering as essential and provide the required pointer and keyboard interactions rather than presenting the static order as equivalent behavior.
+
+## Browser support and fallback strategies
+
+### `moveBefore()`
+
+Browser support for moveBefore(): Limited availability.
+Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), and Firefox 144 (Oct 2025).
+Unsupported in: Safari.
+
+If your Baseline target does not support `moveBefore()`, feature-detect with `'moveBefore' in Element.prototype` and fall back to `referenceNode.before(item)` (or `container.append(item)` when there is no reference node) with the existing item node. Because `before()` removes and reinserts the node, it has two side effects to handle:
+
+- **It drops active pointer capture.** Keep the `pointermove`, `pointerup`, and `pointercancel` listeners on `document`, where captured events still bubble. After the move, re-call `handle.setPointerCapture(event.pointerId)` when `hasPointerCapture()` is false, and end the drag on `lostpointercapture` only if capture is not re-established.
+- **It blurs focused descendants.** Explicitly call `.focus()` on the active handle or movement button after moving. Also delay the live-region update by about 500 ms (debounced, clearing the previous message first), because the focus re-announcement otherwise swallows the position announcement in screen readers such as VoiceOver in Safari.
+
+### `reading-flow`
+
+Browser support for reading-flow: Limited availability.
+Supported by: Chrome 137 (May 2025) and Edge 137 (May 2025).
+Unsupported in: Firefox and Safari.
+
+In browsers that do not support `reading-flow`, sequential focus navigation follows DOM source order. Structure each item's DOM order so interactive controls appear in a logical reading and tab sequence without relying on CSS visual reordering.
+
+### `user-select`
+
+Browser support for user-select: Limited availability.
+Supported by: Chrome 54 (Oct 2016), Edge 79 (Jan 2020), and Firefox 69 (Sep 2019).
+Unsupported in: Safari.
+
+Include `-webkit-user-select: none` before `user-select: none` on the drag handle so text selection stays suppressed during dragging in Safari.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/drag.md b/skills/modern-web-guidance/guides/ui-behaviors/drag.md
index dc58c6d..cf20466 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/drag.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/drag.md
@@ -4,9 +4,7 @@ Add dragging to an existing floating element such as a panel, palette, toolbar,
## Use a dedicated handle
-Start dragging from a dedicated handle when the element contains selectable text, buttons, inputs, or links. This keeps its normal contents usable. Make the handle focusable for keyboard movement and give it an accessible name that mentions the arrow-key interaction.
-
-Do not apply `role="application"` to the handle. It unnecessarily changes assistive-technology interaction.
+Start dragging from a dedicated handle when the element contains selectable text, buttons, inputs, or links. This keeps its normal contents usable. Make the handle focusable for keyboard movement and give it an accessible name that mentions the arrow-key interaction. Ensure the handle exposes a `button` role so that the accessible name is conveyed to screen reader users.
Apply `cursor: grab`/`grabbing`, `touch-action: none`, and both `user-select: none` and `-webkit-user-select: none` to the handle—not the entire draggable element—so text outside it remains selectable and touch gestures retain their usual behavior:
@@ -36,7 +34,8 @@ With pointer capture, the movement listeners can remain on the handle:
```js
handle.addEventListener('pointerdown', (event) => {
- if (event.button !== 0 || event.target.closest('button, input, select, textarea, a')) return;
+ const control = event.target.closest('button, input, select, textarea, a');
+ if (event.button !== 0 || (control && control !== handle)) return;
const rect = draggable.getBoundingClientRect();
offsetX = event.clientX - rect.left;
@@ -71,7 +70,42 @@ When the handle has focus, move the element with the arrow keys and call `preven
## Dialog-specific note
-A `<dialog>` or `[popover]` can use this mechanism with its header as the handle. Set `margin: 0` before assigning `left` and `top`, because the browser's default margins interfere with manual positioning. For dialog and popover opening, closing, focus, and dismissal behavior, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`) and `platform-controls-dismiss-dialog` (via `npx -y modern-web-guidance@latest retrieve "platform-controls-dismiss-dialog"`).
+A `<dialog>` or `[popover]` can use this mechanism with its header in addition to a separate drag handle. Set `margin: 0` before assigning `left` and `top`, because the browser's default margins interfere with manual positioning. For dialog and popover opening, closing, focus, and dismissal behavior, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`) and `platform-controls-dismiss-dialog` (via `npx -y modern-web-guidance@latest retrieve "platform-controls-dismiss-dialog"`).
+
+## Accessibility requirements
+
+The drag handle that is exposed to assistive technologies must be a dedicated button, rather than just scripting the header of a dialog to be draggable. This will ensure the button is exposed to screen reader users with an appropriate role and accessible name. For example, using a native button element:
+
+```html
+<button type="button" aria-label="Notes panel handle. Use arrow keys to move.">
+ <!-- handle icon -->
+</button>
+```
+
+Ensure the draggable element can also be moved or operated using a single pointer without dragging (for example, clicks or taps). What the UI for this looks like depends on the use case. A few examples:
+- Kanban boards: a "move to column" menu or buttons
+- Maps: directional pan buttons
+- Sliders: clicking on the track, and sometimes adjusting the value via a linked `<input>`
+- Floating panels and dialogs: a grid in the background where clicking on a cell in the grid moves the element to the new position or their drag handle may be a menu button, with menu items to reposition the element ("Dock left", "Move left", "Dock top", "Move up", "Dock right", "Move right", "Dock bottom", and "Move down")
+
+Provide feedback for screen reader users when the draggable element is moved. Use a visibly hidden live region, so that any updates to the region are announced to screen reader users. Ensure the region is included on page load, so that it is registered.
+
+```html
+<div class="visually-hidden" aria-live="polite"></div>
+```
+
+Update the region when the draggable element is moved:
+
+```html
+<div class="visually-hidden" aria-live="polite">
+ [Name of element] moved [new position]
+</div>
+```
+
+Do not display raw coordinates for the position, prefer a descriptive name (e.g. "docked left") or omit it if there is no meaningful description.
+The message can be removed after a second, as it will be announced and no longer relevant.
+
+As the keyboard interaction may not be obvious for some users, provide a help button in the draggable element that reveals the keystrokes to perform the operation.
## Fallback strategies
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/dynamic-sort.md b/skills/modern-web-guidance/guides/ui-behaviors/dynamic-sort.md
new file mode 100644
index 0000000..b18e9f6
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/dynamic-sort.md
@@ -0,0 +1,129 @@
+# Handling dynamic user-triggered changes to sort order
+
+Use this pattern when a user action reorders a list, card grid or table, with no item mid-interaction. It covers only applying the new order to the DOM (moving nodes, animating, announcing, performance), not how the order is computed or what triggers it.
+
+## Reorder the existing nodes
+
+**MANDATORY:** Reorder the existing DOM nodes into the new order. Do not recreate them. Recreating nodes with `innerHTML` or a re-render that replaces them discards focus, scroll position inside items, and image state, and it breaks view transitions, which match old and new elements by identity.
+
+Use `moveBefore()` rather than `append()` so moved items keep state such as `<iframe>` content, playing animations, and focus inside them.
+
+```javascript
+// `orderedNodes` is the container's existing child elements in their new order.
+function reorder(container, orderedNodes) {
+ // Moving each node to the end in order is enough; no need to compute minimal moves.
+ for (const node of orderedNodes) container.moveBefore(node, null);
+}
+```
+
+**DO NOT** fake a new order with CSS `order` or `flex-direction: row-reverse`. Visual order and DOM order must match so keyboard and screen reader order follows what the user sees.
+
+### Reordering table rows
+
+For a `<table>`, move the `<tr>` elements within their `<tbody>` using the same function: `reorder(tbody, orderedRows)`. Never reorder header rows in `<thead>` or recreate the `<tbody>`.
+
+## Optionally animate the reorder with view transitions
+
+Animation is an enhancement; the reorder works without it. To animate, wrap the DOM reorder in a view transition and give every item a unique `view-transition-name` so each one animates from its old position to its new one. Without it the list snaps.
+
+Use `view-transition-name: match-element` so you do not need to generate a name per item.
+
+Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 144 (Oct 2025), and Safari 18 (Sep 2024).
+
+```css
+.item {
+ /* Derives a unique name from each element's identity. */
+ view-transition-name: match-element;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ ::view-transition-group(*),
+ ::view-transition-old(*),
+ ::view-transition-new(*) {
+ animation: none;
+ }
+}
+```
+
+```javascript
+function reorderWithTransition(list, orderedNodes) {
+ const update = () => reorder(list, orderedNodes);
+
+ // Prefer a transition scoped to the list: the rest of the page stays interactive.
+ // Fall back to a document-level transition, then to a plain update.
+ if (list.startViewTransition) {
+ list.startViewTransition(update);
+ } else if (document.startViewTransition) {
+ document.startViewTransition(update);
+ } else {
+ update();
+ }
+}
+```
+
+* **Rapid changes:** starting a new view transition skips the one in flight, which is the desired behavior when the user flips through options quickly. Always apply the final state in the update callback so the DOM ends in the correct order even if the animation is skipped.
+* **Large lists:** every named element is captured as an image, so naming hundreds of items is expensive. `match-element` names every matching element too, so it is no cheaper than explicit names. Skip the transition when the list is larger than a few hundred items.
+* **Interactivity:** a document-level view transition blocks pointer events on the whole page while it runs, whereas `list.startViewTransition()` only affects the list's subtree. Prefer the scoped form, and keep the animation brief either way. Names only need to be unique within the scope. For table rows, scope the `<table>` (or a wrapper around it). See `scoped-component-transitions` (via `npx -y modern-web-guidance@latest retrieve "scoped-component-transitions"`) for scoped transition details.
+
+## Announce the change once
+
+Reordering moves many nodes, but the user performed one action. **DO NOT** put `aria-live` on the list, which would announce every moved item. Instead:
+
+* Add one visually hidden `role="status"` element and set its text once per reorder, after starting the update. It must already be in the DOM before its text changes.
+* Name the result, not the mechanism: "Sorted by price, low to high, 24 items".
+* Keep focus on the control that triggered the change. Do not move focus into the list.
+* Make the current order readable from the control itself, so a screen reader user who lands on it hears what is selected without searching the page. Native controls (`<select>`, radios) do this already; for toggle buttons use `aria-pressed` and label the current state, not the action.
+
+```html
+<p id="reorder-status" role="status" class="visually-hidden"></p>
+```
+
+```css
+/* Hides the status text visually but keeps it available to screen readers. Do not use display: none. */
+.visually-hidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
+```
+
+```javascript
+reorderWithTransition(list, orderedNodes);
+// Set the message once, not once per item.
+status.textContent = `Sorted by price, low to high, ${orderedNodes.length} items`;
+```
+
+## Performance on large lists
+
+* Layout and rendering are the cost, not computing the order. Reorder nodes in a single pass with no layout reads (`offsetTop`, `getBoundingClientRect()`) in the loop.
+* Add `content-visibility: auto` with `contain-intrinsic-size` to items in long lists so off-screen items skip rendering work.
+* Above roughly a thousand items, virtualize the list instead of keeping every node in the DOM. Skip the view transition when virtualizing.
+* For expensive reorders (very large lists, or an order set through several inputs), apply the new order only when the user confirms it, for example with an Apply button, instead of on every input change.
+
+## Fallbacks
+
+Browser support for Element-scoped view transitions: Limited availability.
+Supported by: Chrome 147 (Apr 2026) and Edge 147 (Apr 2026).
+Unsupported in: Firefox and Safari.
+
+If your Baseline target does not support `element.startViewTransition()`, use `document.startViewTransition()`. If it does not support that either, reorder without animation. The list still sorts correctly and the announcement is unchanged, so this is graceful degradation: the animation enhances the use case but is not core to it.
+
+Browser support for moveBefore(): Limited availability.
+Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), and Firefox 144 (Oct 2025).
+Unsupported in: Safari.
+
+If your Baseline target does not support `moveBefore()`, use `append()`. DOM order is identical; items may lose focus, iframe, or animation state inside them, which only matters when items contain such state.
+
+```javascript
+function reorder(container, orderedNodes) {
+ const move = Object.hasOwn(Element.prototype, 'moveBefore')
+ ? (node) => container.moveBefore(node, null)
+ : (node) => container.append(node);
+
+ for (const node of orderedNodes) move(node);
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md b/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md
index 1ea3b26..be67fe3 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/group-element-transitions.md
@@ -1,118 +1,125 @@
-# Group Element Transitions
+# Smoothly rearrange cards, lists, and groups of elements on add, remove, or reorder
As items are added or removed from a list, or rearranged, transitions can help users maintain context. View transitions provide a way to transition between two states of an element by giving the element a unique `view-transition-name`. When multiple elements on a page share the same transition behavior, `view-transition-class` allows you to define that logic once in CSS rather than repeating it for every unique `view-transition-name`. This keeps your stylesheets maintainable while ensuring consistent animations across a group of elements.
-### Implementation steps
+## Implementation steps
1. **Assign unique names and a shared class**
-Each element that needs to be tracked individually during a transition must have a unique `view-transition-name`.
+ Each element that needs to be tracked individually during a transition must have a unique `view-transition-name`.
-```html
-<!-- Mandatory: Each element must have a unique view-transition-name -->
-<li style="view-transition-name: item-1" class="item">Item 1</li>
-<li style="view-transition-name: item-2" class="item">Item 2</li>
-```
+ ```html
+ <!-- Mandatory: Each element must have a unique view-transition-name -->
+ <li style="view-transition-name: item-1" class="item">Item 1</li>
+ <li style="view-transition-name: item-2" class="item">Item 2</li>
+ ```
-To apply shared styles, also assign a `view-transition-class`.
+ To apply shared styles, also assign a `view-transition-class`.
-```css
-.item {
- view-transition-class: list-item;
-}
-```
+ ```css
+ .item {
+ view-transition-class: list-item;
+ }
+ ```
2. **Define the shared transition logic**
-
-Use the `::view-transition-group()` pseudo-element with the class selector to apply styles to all members of that group.
-
-```css
-/* Targets any view transition group that has the 'list-item' class */
-::view-transition-group(.list-item) {
- animation-duration: 0.5s;
- animation-timing-function: ease-in-out;
-}
-
-/* Handle accessibility by respecting motion preferences */
-@media (prefers-reduced-motion: reduce) {
- /* Disable all group transitions, including the default `root` group. */
- ::view-transition-group(*),
- ::view-transition-old(*),
- ::view-transition-new(*) {
- animation: none !important;
- }
-}
-```
-
-3. **Optional: Define entry and exit animations**
-Use the `:only-child` selector to add specific transitions to the elements that are added or removed. `::view-transition-new()` and `::view-transition-old()` pseudo-elements are children of a `::view-transition-image-pair()` pseudo-element, so we can determine it is an added or removed element if it is the only child.
-
-```css
-/* A `::view-transition-new()` element is the only child if it wasn't present before the view transition, so it is an added element. */
-::view-transition-new(.list-item):only-child {
- animation-name: slide-in;
- /* Specify an animation duration if you want something different than the UA default of 0.5s */
- animation-duration: 1s;
-}
-/* A `::view-transition-old()` element is the only child if it isn't present after the view transition, so it is a removed element. */
-::view-transition-old(.list-item):only-child {
- animation-name: slide-out;
- /* Specify an animation duration if you want something different than the UA default of 0.5s */
- animation-duration: 1s;
-}
-
-@keyframes slide-in {
- from {
- translate: -100vw 0;
- }
-}
-@keyframes slide-out {
- to {
- translate: -100vw 0;
- }
-}
-```
+ Use the `::view-transition-group()` pseudo-element targeting a `view-transition-class` to apply animation styles to all members of that group.
+
+ ```css
+ /* Targets any view transition group that has the 'list-item' view-transition-class */
+ ::view-transition-group(.list-item) {
+ /* Duration and non-linear easing are examples; customize with any ease* keyword, cubic-bezier(), or multi-stop linear() curve */
+ animation-duration: 0.5s;
+ animation-timing-function: ease-in-out;
+ }
+
+ /* Handle accessibility by respecting motion preferences */
+ @media (prefers-reduced-motion: reduce) {
+ /* Disable all group transitions, including the default `root` group. */
+ ::view-transition-group(*),
+ ::view-transition-old(*),
+ ::view-transition-new(*) {
+ animation: none !important;
+ }
+ }
+ ```
+
+3. **Define entry and exit animations (when adding or removing items)**
+
+ Use the `:only-child` selector to add specific transitions to the elements that are added or removed. `::view-transition-new()` and `::view-transition-old()` pseudo-elements are children of a `::view-transition-image-pair()` pseudo-element, so we can determine it is an added or removed element if it is the only child. Entry effects typically use a curve that eases out (such as `ease-out`) so added items decelerate into place, whereas exit effects typically use a curve that eases in (such as `ease-in`) so removed items accelerate away.
+
+ ```css
+ /* A `::view-transition-new()` element is the only child if it wasn't present before the view transition, so it is an added element. */
+ ::view-transition-new(.list-item):only-child {
+ animation-name: slide-in;
+ /* Override the duration inherited from ::view-transition-group(.list-item) if desired (example value) */
+ animation-duration: 1s;
+ /* Entry effects typically ease out as the element settles into place */
+ animation-timing-function: ease-out;
+ }
+ /* A `::view-transition-old()` element is the only child if it isn't present after the view transition, so it is a removed element. */
+ ::view-transition-old(.list-item):only-child {
+ animation-name: slide-out;
+ /* Override the duration inherited from ::view-transition-group(.list-item) if desired (example value) */
+ animation-duration: 1s;
+ /* Exit effects typically ease in as the element leaves */
+ animation-timing-function: ease-in;
+ }
+
+ @keyframes slide-in {
+ from {
+ translate: -100vw 0;
+ }
+ }
+ @keyframes slide-out {
+ to {
+ translate: -100vw 0;
+ }
+ }
+ ```
4. **Trigger the transition**
-Wrap the DOM update in `document.startViewTransition()`. The browser will capture the old state, perform the update, and then animate to the new state.
+ Wrap the DOM update in `document.startViewTransition()`. The browser will capture the old state, perform the update, and then animate to the new state.
-```javascript
-function updateList(newData) {
- document.startViewTransition(() => {
- // All DOM changes inside this callback will be transitioned
- render(newData);
- });
-}
-```
+ ```javascript
+ function updateList(newData) {
+ document.startViewTransition(() => {
+ // All DOM changes inside this callback will be transitioned
+ render(newData);
+ });
+ }
+ ```
5. **Maintain interactivity of non-transitioned elements**
-View transitions work by overlaying snapshots of the DOM elements, and then transitioning the snapshots. This means that during the transition, elements are not interactive. If there are interactive elements that are not transitioned, you can make them interactive by disabling touch events on the view transitions.
+ View transitions work by overlaying snapshots of the DOM elements, and then transitioning the snapshots. This means that during the transition, elements are not interactive. If there are interactive elements that are not transitioned, you can make them interactive by disabling pointer events on the view transitions.
-```css
-::view-transition {
- /* Non-transitioned elements below the view transitions remain interactive */
- pointer-events: none;
-}
-```
+ ```css
+ ::view-transition {
+ /* Non-transitioned elements below the view transitions remain interactive */
+ pointer-events: none;
+ }
+ ```
-In addition, by default, the `:root` element has a view transition named `root`, which enables default full-page transitions. If there are no changes to the root element, this will be a transition between two identical snapshots, which are not interactive. Because we are only transitioning specific elements, and not the entire screen, we can disable the `root` transition.
+ In addition, by default, the `:root` element has a view transition named `root`, which enables default full-page transitions. If there are no changes to the root element, this will be a transition between two identical snapshots, which are not interactive. Because we are only transitioning specific elements, and not the entire screen, we can disable the `root` transition.
-```css
-:root {
- /* Disable the root transition because we are only transitioning specific elements. */
- view-transition-name: none;
-}
-```
+ ```css
+ :root {
+ /* Disable the root transition because we are only transitioning specific elements. */
+ view-transition-name: none;
+ }
+ ```
-### Fallback strategies
+## Fallback strategies
-Baseline status for view-transition-class: Newly available. It's been Baseline since 2025-10-14.
-Supported by: Chrome 125 (May 2024), Edge 125 (May 2024), Firefox 144 (Oct 2025), and Safari 18.2 (Dec 2024).
+### View transitions
-View Transitions are a progressive enhancement. If the browser does not support `document.startViewTransition`, the DOM update should still occur immediately, providing a functional but non-animated experience.
+Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 144 (Oct 2025), and Safari 18 (Sep 2024).
+
+View Transitions are a progressive enhancement. If the browser does not support `document.startViewTransition`, run the DOM update immediately to provide a functional, non-animated experience:
```javascript
if (document.startViewTransition) {
@@ -123,4 +130,9 @@ if (document.startViewTransition) {
}
```
-For CSS, browsers that do not recognize `view-transition-class` or the `::view-transition-group()` class selector will simply ignore those rules, and no animation will be applied.
+### `view-transition-class`
+
+Baseline status for view-transition-class: Newly available. It's been Baseline since 2025-10-14.
+Supported by: Chrome 125 (May 2024), Edge 125 (May 2024), Firefox 144 (Oct 2025), and Safari 18.2 (Dec 2024).
+
+Browsers that do not recognize `view-transition-class` or the `::view-transition-group(.class)` selector ignore those CSS rules while still running the DOM update (and any base view transition if supported).
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/highlight-text-ranges.md b/skills/modern-web-guidance/guides/ui-behaviors/highlight-text-ranges.md
index 87e875a..8a68dd6 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/highlight-text-ranges.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/highlight-text-ranges.md
@@ -2,11 +2,12 @@
The CSS Custom Highlight API lets you style arbitrary text ranges on a page without modifying the DOM structure. This enables search-result highlighting, syntax coloring, collaborative editing cursors, or spelling and grammar error markers without wrapping text in extra elements or relying on `innerHTML` manipulation.
-### Core implementation
+## Core implementation
To highlight text ranges, you must collect the target text nodes, create `Range` and `Highlight` objects, register them in the `HighlightRegistry`, and then style them with the `::highlight()` pseudo-element.
-#### 1. Collect text nodes and create ranges
+### 1. Collect text nodes and create ranges
+
Use a `TreeWalker` to collect all text nodes in the target element, then create `Range` objects pointing at the character offsets you want to highlight.
```javascript
@@ -29,14 +30,16 @@ range.setEnd(textNode, matchEndIndex);
Cache the text-node list and only rebuild it when the DOM content actually changes, since walking the tree is expensive.
-#### 2. Create a Highlight from the ranges
+### 2. Create a Highlight from the ranges
+
Group one or more `Range` objects into a `Highlight`. Multiple ranges that share the same style belong in a single highlight.
```javascript
const searchHighlight = new Highlight(...matchingRanges);
```
-#### 3. Register the highlight in the registry
+### 3. Register the highlight in the registry
+
Register each `Highlight` under a custom name using `CSS.highlights`, which is a `Map`-like `HighlightRegistry`.
```javascript
@@ -60,27 +63,33 @@ CSS.highlights.set("primary", primary);
CSS.highlights.set("secondary", secondary);
```
-#### 4. Style with `::highlight()`
+### 4. Style with `::highlight()`
+
Use the `::highlight()` pseudo-element in CSS to style each registered highlight by name.
```css
::highlight(search-results) {
- background-color: #ffdd00;
- color: black;
+ background-color: #0000FF;
+ color: white;
}
```
Only a limited set of CSS properties work inside `::highlight()`: `color`, `background-color`, `text-decoration` and its longhands, `text-shadow`, `-webkit-text-stroke-color`, `-webkit-text-fill-color`, and `-webkit-text-stroke-width`. Properties like `background-image`, `font-size`, or `padding` are ignored.
-### Accessibility
+## Accessibility
**AVOID**: using custom highlights as a replacement for semantic HTML.
-Custom highlights are purely presentational and are not exposed to the accessibility tree. If the highlighted text is semantically relevant to the document (e.g., a user-selected passage), use `<mark>` instead. Reserve custom highlights for transient, visual-only effects like search results or syntax coloring.
+Custom highlights are purely presentational and are not exposed to the accessibility tree. If the highlighted text is semantically relevant to the document (e.g., a user-selected passage), or where the highlight conveys meaning (e.g., to indicate a heading element or an ARIA attribute in an HTML tutorial to demonstrate how it is used), use `<mark>` instead. Reserve custom highlights for transient, visual-only effects like search results, or syntax coloring where the meaning can be derived from nearby indicators (e.g., a "+" sign before the highlighted text to indicate syntax that has been added).
+
+Make sure that there is sufficient contrast between the highlight background color and text color to meeting WCAG 2.2 Success Criterion 1.4.3 Contrast (Minimum) (Level AA). The contrast ratio must be at least 4.5:1 for text with a font size of less than 18 point or 14 point bold, and at least 3:1 for text with a font size of greater than 18 point or 14 point bold.
+
+Make sure that the contrast ratio between the highlight background color and adjacent colors is at least 3:1 to meet WCAG 2.2 Success Criterion 1.4.11 Non-text Content (Level AA).
+The contrast can be less than 3:1 if the highlighted text uses another visual indicator (e.g. `text-decoration: underline;` or the inclusion of a subtle `text-shadow` on the text) to further indicate that the text is highlighted.
-Highlights should not rely solely on color to convey meaning. If a highlight indicates an error, pair it with another visual indicator such as `text-decoration: wavy underline` or an adjacent text label. Ensure sufficient contrast between the highlight background and text color to meet WCAG 2.1 requirements (at least 4.5:1 for normal text).
+Highlights must not rely solely on color to convey meaning. For example, if a highlight indicates an error, pair it with another visual indicator such as `text-decoration: wavy underline`, an adjacent text label, or an icon.
-### Fallback strategies
+## Fallback strategies
Baseline status for Custom highlights: Newly available. It's been Baseline since 2026-03-24.
Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 149 (Mar 2026), and Safari 17.2 (Dec 2023).
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/interactive-content-reveal.md b/skills/modern-web-guidance/guides/ui-behaviors/interactive-content-reveal.md
index 843cbae..249a3e0 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/interactive-content-reveal.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/interactive-content-reveal.md
@@ -45,15 +45,15 @@ Apply the `mask-image` to the element you want to reveal. Use a `radial-gradient
pointer-events: none;
}
-/* Update the gradients stops on interaction */
-.reveal-layer:hover {
+/* Update the gradient stops when hovering the interactive container (inherits into .reveal-layer; .reveal-layer itself has pointer-events: none) */
+.container:hover {
--inner-size: 100px;
--outer-size: 120px;
-}
+}
```
### 3. Update Coordinates with JavaScript
-Track the pointer position and update the CSS variables. Because the properties are registered and have a `transition` defined, the spotlight will move smoothly even if the pointer events are infrequent.
+Track the pointer position and update the CSS variables on pointermove events. Because position variables update immediately without transition, the spotlight follows the pointer directly while the size properties expand or contract smoothly.
```javascript
const container = document.querySelector('.container');
@@ -70,7 +70,7 @@ container.addEventListener('pointermove', (e) => {
const x = ((e.clientX - rect.left) / rect.width) * 100;
const y = ((e.clientY - rect.top) / rect.height) * 100;
- // Update the registered properties
+ // Update the position properties
container.style.setProperty('--mouse-x', `${x}%`);
container.style.setProperty('--mouse-y', `${y}%`);
});
@@ -91,6 +91,13 @@ container.addEventListener('pointermove', (e) => {
}
```
+Make sure that all underlying content can still be reached even at very high zoom levels. In particular, make sure that all content that uses this pattern:
+
+* Can be scaled up to 200% using a browser's built-in zoom without loss of functionality
+* Is visible and operable without requiring two-dimensional scrolling when scaled up to 400% in a starting viewport size of 1280 CSS pixels by 1024 CSS pixels
+
+Make sure that transitions do not flash more than three times in any one second period.
+
## Fallback strategies
Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-action-previews.md b/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-action-previews.md
index 6fd4bff..252bcd9 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-action-previews.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-action-previews.md
@@ -52,7 +52,7 @@ The start and end delay for an interest invoker (i.e. the element with the `inte
### Fallbacks & browser support for Interest invokers
Browser support for Interest invokers: Limited availability.
-Supported by: Chrome 142 (Oct 2025) and Edge 142 (Oct 2025).
+Supported by: Chrome 149 (Jun 2026) and Edge 149 (Jun 2026).
Unsupported in: Firefox and Safari.
Interest invokers must be conditionally polyfilled using the `interestfor` polyfill package from NPM. Prefer bundling the polyfill over using the CDN.
@@ -61,7 +61,7 @@ Interest invokers must be conditionally polyfilled using the `interestfor` polyf
```html
<script type="module">
- if (!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")) {
+ if (!("interestForElement" in HTMLButtonElement.prototype)) {
// CDN link only used for example, prefer bundling.
await import("https://unpkg.com/interestfor@latest");
}
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md b/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md
index fe2f660..c406359 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/interest-triggered-tooltips.md
@@ -2,6 +2,14 @@
Users expect to see additional related information without completely changing their context. Showing a tooltip when a user is interested in more information can be useful to provide definitions for a term, clarifying the action an icon-only button will take, or provide additional form field guidance.
+## Should you use a tooltip?
+
+A toggletip is a small button, usually an "i" or "?" icon, placed next to a control or a piece of content, whose only job is to reveal more information. The choice between tooltip, toggletip, and inline content is about how important and how long the information is:
+
+- **Tooltip** (on the control itself): a short clarification of what the control does. Missing it costs the user little.
+- **Toggletip** (an "i" or "?" next to the control or content): information users may well want but most don't need every time, such as why a field is required, how a total was computed, or what a policy means, or anything longer than a phrase. Showing it inline would add clutter, but it deserves an explicit, visible affordance so every user can find it deliberately rather than by happening to hover, including on touch and with a screen reader. See below for guidance on creating toggletips.
+- **Inline content**: information most users need in order to act, or need while they act (password rules while typing, a value they copy). A popover closes as soon as they click or focus elsewhere.
+
## Creating the tooltip
You can create a popover with the required behavior by adding the `popover="hint"` attribute to a `<div>` or other semantically appropriate element. When the user opens the tooltip, this hides other `popover="hint"` tooltips, but doesn't hide `auto` or `manual` tooltips. It also handles dismissing nested tooltips.
@@ -11,8 +19,8 @@ It also provides light dismiss behavior, so when a user clicks or otherwise focu
The tooltip element must have an `id` attribute with a unique value:
```html
-<!-- MANDATORY: The tooltip container `<div>` must have a `popover` attribute.
- the value of `"hint"` ensures it can be "light dismissed". -->
+<!-- MANDATORY: The tooltip element must have popover="hint" so it light-dismisses
+ without closing unrelated auto or manual popovers. -->
<div popover="hint" id="tooltip">Tooltip content</div>
```
@@ -22,19 +30,41 @@ A user expresses interest in the additional information by hovering or focusing
<!-- The `interestfor` attribute can be applied to a `<button>` element: -->
<button interestfor="tooltip">Tooltip trigger</button>
-<!-- The `interestfor` attribute can also be applied to an `<a>` element: -->
-<a interestfor="tooltip" href="">Tooltip trigger</a>
+<!-- The `interestfor` attribute can also be applied to an `<a>` element (href is an example): -->
+<a interestfor="tooltip" href="/docs/dom">Tooltip trigger</a>
```
The trigger must have a visual indicator to indicate that there is additional information available by interacting with the trigger.
-### Accessibility built in to `interestfor`
+### Accessibility
+
+`interestfor` is specified to wire hint popovers (`popover="hint"`) for assistive technology itself, based on what the target contains. A **plain hint** (text and images only) becomes the trigger's accessible description, or its name if it has none. A **rich hint** (headings, links, or other interactive content) gets a minimum role of `tooltip`, the trigger gets `aria-expanded` and an `aria-details` relation while the hint is open, and the open hint comes right after the trigger in the tab order so keyboard users can reach its content.
+
+Browsers and screen readers do not yet expose this consistently, so add explicit ARIA as well:
+
+- **Hint that repeats the trigger's accessible name** (e.g. an icon-only button with `aria-label="Bold"` and a "Bold" tooltip): add nothing. A description identical to the name would be read twice.
+- **Hint on a trigger with no visible label of its own** (e.g. an icon-only button without `aria-label`): `aria-labelledby` on the trigger pointing at the hint, so the hint becomes the name.
+- **Hint whose trigger also opens it on activation** (a toggletip, or any button whose only job is the hint: give it `popovertarget` with `popovertargetaction="show"`): `role="tooltip"` on the hint and `aria-expanded` on the trigger, kept in sync with the popover's `toggle` event. A description read right after "button" suggests further actions and muddles the role; the expanded state tells the user there is content to reveal and whether it is open, and pressing the button delivers it. Place the hint right after the trigger in the DOM so reading keys reach its content once it is open.
+- **Hint whose trigger does something else on activation** (a link, a button with its own action): `role="tooltip"` on the hint and `aria-describedby` on the trigger, never `aria-expanded`. A trigger announced as "collapsed" suggests `Enter` would expand it, but `Enter` navigates or acts. The hint must be something the user can afford to miss: a hovercard previews the destination, a tooltip on an action button describes the action.
+- **DO NOT** attach a hint that opens on activation to a control that already uses `aria-expanded` for something else (for example, a menu button). Give that hint its own trigger instead.
+- **DO NOT** move focus into the target when interest is shown (no `autofocus`, no `focus()` in an `interest` listener). Interest is triggered by hover or focus alone, so moving focus would fail WCAG 3.2.1 (On Focus).
+
+Not every screen reader reads descriptions when moving through the page (NVDA skips them in browse mode by design), so a hint exposed as a description must only carry content the user can afford to miss. Link previews and tooltips on action controls qualify; anything the user needs belongs in a toggletip or inline.
-When you use `interestfor`, the browser handles the assistive-technology wiring for you:
+Wire this with a short script instead of hand-authoring the attributes, so the markup stays declarative and the same rules apply to every hint. The script should:
-- **Implicit semantics:** A target with `popover="hint"` gains an implicit minimum role of `tooltip`. **DO NOT** set `role="tooltip"` yourself.
-- **Implicit association:** The browser implicitly associates the source element with the target via `aria-describedby` when the target is plaintext, or via `aria-details` when the target contains interactive content. **DO NOT** add `aria-describedby` or `aria-details` to the trigger.
-- **Interactive content:** Because the association switches to `aria-details` when needed, the target IS allowed to contain interactive content (e.g. a link inside an "interest card").
+1. Run in every browser, before loading the `interestfor` polyfill, once the DOM is parsed, and expose a function that can be called again for content inserted later. Scanning upfront is required: a browse-mode screen reader user needs the attributes in place before any interaction, so wiring them lazily on `focus` or `interest` is too late, and so is waiting for the polyfill, which wires its ARIA only on `load` and adds no `role="tooltip"` to plain hints.
+2. For every `[interestfor]` trigger whose target has `popover="hint"`, normalize whitespace and compare the hint text with the trigger's accessible name (`aria-labelledby` targets, else `aria-label`, else text content including image `alt`, else `title`). Equal: do nothing. Otherwise set `role="tooltip"` on the hint if it has no role.
+3. When the trigger has no name, point `aria-labelledby` at the hint unless it already has one. Otherwise, if the trigger also opens the hint on activation (a `popovertarget` or `commandfor` naming the hint), set `aria-expanded` to the popover's current state (`:popover-open`) unless it already has `aria-expanded`, and remember which triggers the script owns; if not, point `aria-describedby` at the hint unless it already has one.
+4. Keep `aria-expanded` in sync from the popover's `toggle` event in every browser with a single capturing listener on `document`, updating every trigger with a matching `interestfor` that the script owns (the `interestfor` polyfill does not sync `aria-expanded` on plain-text hints or when a toggletip is opened via `popovertarget`).
+
+Things that are easy to get wrong:
+
+- `toggle` does not bubble. A bubbling listener on `document` never fires; use the capture phase (or a listener per popover).
+- Sync `aria-expanded` from `toggle`, not from `interest`/`loseinterest`. The popover is the source of truth: it can be closed by `Escape`, light dismiss, or another invoker, and several triggers can share one hint.
+- A hidden popover is a valid `aria-describedby` or `aria-labelledby` target. Do not force the hint open or duplicate its text to make it "visible".
+- Do not add `aria-haspopup` or a live region to any hint.
+- Do not override author ARIA: an existing `aria-describedby`, `aria-labelledby`, or `aria-expanded` on the trigger wins.
### Accessibility Constraints (WCAG 1.4.13)
@@ -52,18 +82,36 @@ In modern browsers supporting native anchor positioning, you do **not** need to
```css
[popover] {
/* Implicit anchor from interestfor: no anchor-name or position-anchor needed */
- position-area: top;
+ position-area: block-start;
position-try-fallbacks: flip-block;
- margin: unset;
+ /* Override UA popover centering (`inset: 0; margin: auto`) so the tooltip sits adjacent to its anchor */
+ inset: auto;
+ margin: 0;
}
```
-### Fallback strategies
+## Toggletips: an "i" or "?" button
+
+Give a toggletip both triggers: `interestfor` opens it on hover, focus, and long-press; `popovertarget` opens it on click, tap, and `Enter`.
+
+```html
+<label>Shipping <input name="shipping"></label>
+<!-- The name says what the button reveals; the "?" alone is not a name. -->
+<button type="button" interestfor="shipping-help" popovertarget="shipping-help" popovertargetaction="show" aria-label="More about shipping">?</button>
+<!-- Right after the trigger, so it reads in sequence. -->
+<div id="shipping-help" popover="hint">Free shipping applies to orders over $50. Orders placed before 2pm ship the same day.</div>
+```
+
+- Use `popovertargetaction="show"`, not the default `toggle`: hover has usually opened the popover already, and a toggle would close it on the click that follows. `Escape`, light dismiss, and losing interest close it.
+- Keep `popover="hint"`: hovering across a toggletip must not close an open menu, which an `auto` popover would.
+- Position it like any tooltip. The button is the popover's implicit anchor through either attribute.
+
+## Fallback strategies
### Fallbacks & browser support for Interest invokers
Browser support for Interest invokers: Limited availability.
-Supported by: Chrome 142 (Oct 2025) and Edge 142 (Oct 2025).
+Supported by: Chrome 149 (Jun 2026) and Edge 149 (Jun 2026).
Unsupported in: Firefox and Safari.
Interest invokers must be conditionally polyfilled using the `interestfor` polyfill package from NPM. Prefer bundling the polyfill over using the CDN.
@@ -72,7 +120,7 @@ Interest invokers must be conditionally polyfilled using the `interestfor` polyf
```html
<script type="module">
- if (!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")) {
+ if (!("interestForElement" in HTMLButtonElement.prototype)) {
// CDN link only used for example, prefer bundling.
await import("https://unpkg.com/interestfor@latest");
}
@@ -116,22 +164,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -139,41 +181,109 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
+### Fallbacks & browser support for `popover="hint"`
Browser support for popover="hint": Limited availability.
Supported by: Chrome 151 (Jul 2026), Edge 151 (Jul 2026), and Firefox 153 (Jul 2026).
Unsupported in: Safari.
-The `popover-polyfill` does not polyfill the hint behavior in browsers that support `popover` but not `popover="hint"`. For those browsers, a tooltip opened via focus may stay open when a second tooltip opened via hover.
+The `@oddbird/popover-polyfill` package does not polyfill `popover="hint"` in browsers that already support native `popover` (`auto` and `manual`). In those browsers, the unrecognized `"hint"` value defaults to `popover="manual"` (the HTML invalid value default), so a tooltip opened via keyboard focus may remain open if a second tooltip is opened via pointer hover unless explicitly dismissed on loss of interest by the invoker.
+
+A toggletip can also be opened by click, with no interest to lose, so a `manual` fallback would never close. Where `hint` is unsupported, switch toggletips to `popover="auto"` as they open. This MUST happen in `beforetoggle`: the browser reads the popover type after that event, whereas changing the type of an already open popover closes it. `beforetoggle` does not bubble, so delegate with a capturing listener:
+
+```js
+// The `popover` property reports the state the browser actually uses: "manual" when `hint` is unsupported.
+const probe = document.createElement("div");
+probe.popover = "hint";
+if (probe.popover !== "hint") {
+ document.addEventListener("beforetoggle", ({ target, newState }) => {
+ const toggletip = target.getAttribute("popover") === "hint"
+ && document.querySelector(`[popovertarget="${CSS.escape(target.id)}"]`);
+ if (newState === "open" && toggletip) {
+ target.popover = "auto";
+ }
+ }, true);
+}
+```
+
+### Fallbacks & browser support for Anchor positioning
Browser support for Anchor positioning: Limited availability.
Supported by: Safari 27 (Sep 2026).
Unsupported in: Chrome, Edge, and Firefox.
-To support browsers without anchor positioning, you can use the `@oddbird/css-anchor-positioning` polyfill. Alternatively, you can use `@supports` to specify a fallback position.
+Without CSS Anchor Positioning, tethered elements such as `[popover]` overlays fall back to their default user-agent placement (centered in the viewport for popovers). Depending on whether spatial tethering is required for your use case, either conditionally load the polyfill or gate your positioning rules with `@supports`.
+
+#### Option 1: Polyfill (`@oddbird/css-anchor-positioning`)
+
+When the positioned element must stay spatially tethered to its trigger in unsupported browsers, conditionally load the `@oddbird/css-anchor-positioning` package.
-When using the `@oddbird/css-anchor-positioning` polyfill for legacy browser support, be aware that the polyfill does not support implicit anchors or `position-area` on popovers. Explicitly set an `anchor-name` on the trigger, set `position-anchor` on the popover, and position using `anchor()` inset functions instead of `position-area`:
+**MANDATORY:** Feature-detect support via `CSS.supports("anchor-name: --a")` (or `"anchorName" in CSSStyleDeclaration.prototype`), and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature-detect anchor positioning support before loading the polyfill.
+if (!CSS.supports("anchor-name: --a")) {
+ import("@oddbird/css-anchor-positioning");
+}
+```
+
+Without a bundler, import from a CDN inside a `<script type="module">`:
```html
<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->
<script type="module">
- if (!("anchorName" in document.documentElement.style)) {
- await import("https://unpkg.com/@oddbird/css-anchor-positioning");
+ if (!CSS.supports("anchor-name: --a")) {
+ import("https://unpkg.com/@oddbird/css-anchor-positioning");
}
</script>
```
+**Polyfill caveats:**
+- **No implicit anchors:** The polyfill does not support implicit anchor associations (such as those created by `popovertarget`, `commandfor`, `interestfor`, or `showPopover({ source })`). You **MUST** set a unique explicit `anchor-name` on each trigger and a matching `position-anchor` on the positioned element.
+- **No `position-area` with `position-try-fallbacks`:** `position-area` with `position-try-fallbacks` is not supported by the polyfill. When using the polyfill on elements needing fallbacks, position elements using `anchor()` functions on inset properties (`top`, `left`, `right`, `bottom`) with `inset: auto` instead of `position-area`.
+- **Do not wrap polyfilled rules in `@supports`:** Browsers without native anchor positioning evaluate `@supports (position-area: ...)` and `@supports (anchor-name: --a)` to `false` and discard the block before the polyfill can process it.
+
```css
-button[interestfor="tooltip-attrs"] {
- /* MANDATORY: Each trigger and popover pair must have a unique anchor name, referenced by `anchor-name` on the trigger and `position-anchor` on the popover. */
- anchor-name: --tooltip-attrs;
+.trigger {
+ /* MANDATORY: Each trigger and positioned element pair must share a unique anchor name. */
+ anchor-name: --my-trigger;
}
-#tooltip-attrs {
- position-anchor: --tooltip-attrs;
- /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions, and not `position-area. */
+
+[popover].anchored-overlay {
+ position-anchor: --my-trigger;
+ /* MANDATORY: Use anchor() on inset properties rather than position-area when using the polyfill on elements needing position-try-fallbacks. */
+ inset: auto;
top: anchor(bottom);
- left: anchor(right);
- margin: unset;
+ left: anchor(left);
+ margin: 0;
}
-```
\ No newline at end of file
+```
+
+#### Option 2: Progressive enhancement with `@supports` (no polyfill)
+
+If you do not ship the polyfill, **DO NOT** set `inset: auto` or `margin: 0` unconditionally on a `[popover]` element that relies on `position-area` or `anchor()`. In browsers without anchor positioning, `inset: auto` overrides the user-agent centering (`inset: 0; margin: auto`) while `position-area` is ignored, leaving the popover stranded at `(0, 0)` or overlapping its trigger.
+
+Instead, gate `inset: auto` and `margin: 0` inside `@supports` for the specific positioning feature used (for example, `@supports (position-area: block-end)` or `@supports (top: anchor(bottom))`) so unsupported browsers retain the default centered popover placement, or provide a matching `@supports not (...)` fallback layout (such as a fixed bottom sheet):
+
+```css
+@supports (position-area: block-end) {
+ [popover].anchored-overlay {
+ inset: auto;
+ margin: 0;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
+ }
+}
+
+@supports not (position-area: block-end) {
+ /* Optional: override default popover centering with a fixed bottom bar */
+ [popover].anchored-overlay {
+ position: fixed;
+ inset: auto 0 0 0;
+ width: auto;
+ margin: 0;
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/light-dismiss-a-dialog.md b/skills/modern-web-guidance/guides/ui-behaviors/light-dismiss-a-dialog.md
index a44821e..6fef5fa 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/light-dismiss-a-dialog.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/light-dismiss-a-dialog.md
@@ -45,10 +45,13 @@ dialog::backdrop {
- **MANDATORY**: Use `closedby="any"` to enable light-dismiss declaratively.
- **MANDATORY**: Always open modal dialogs with `showModal()`. This ensures the dialog is in the top layer, focus is trapped, and the `Esc` key is handled.
+- **DO**: Ensure that there is always a close button visible to provide people with a clear, alternative way to close the modal dialog.
- **DO**: Use `aria-labelledby` or `aria-label` to provide an accessible name for the dialog.
- **DO NOT**: Use `closedby` for non-modal dialogs (opened with `show()`), as they do not have a backdrop and won't trigger light-dismiss.
- **DO NOT**: Use the `click` event for critical logic that should happen *before* closing; instead, listen for the `close` or `cancel` events.
+Ensure that there aren't components in the modal dialog that themselves use the `Esc` key for interaction, as this may lead to the dialog being inadvertently closed. If the modal dialog does include components that use the `Esc` key (e.g. a menu or a combobox), ensure that when these components are focused, they capture the `Esc` key press and use it accordingly, and that the dialog is not closed accidentally.
+
## Fallback strategies
Browser support for <dialog closedby>: Limited availability.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/motion.md b/skills/modern-web-guidance/guides/ui-behaviors/motion.md
index b617263..b76a935 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/motion.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/motion.md
@@ -1,10 +1,10 @@
# Motion
-- Use `clip-path` and `mask-image` for custom geometric reveals and smooth fade-outs.
+- Use `clip-path` and `mask-image` for custom geometric reveals and smooth fade-outs. Both also clip the element's own focus outline, so when the clipped or masked element is focusable (for example, a scroll container with `tabindex="0"`), draw its focus indicator on a parent element that isn't clipped or masked.
- Use **Scroll-Driven Animations** (`animation-timeline: scroll()`) for non-essential scroll-bound effects instead of JS listeners.
- Use **View Transitions** to animate between complex layout states seamlessly.
-### Performance
+## Performance
- Prefer to animate `opacity` and `transform` (including individual transform properties, e.g. `translate` instead of `left/right/top/bottom`) to ensure animations stay on the compositor thread.
- Use `transition-behavior: allow-discrete`, `@starting-style`, and (for top-layer elements like `<dialog>` or `[popover]`) `overlay` to animate discrete entry and exit states natively; see `animate-element-entry-exit` (via `npx -y modern-web-guidance@latest retrieve "animate-element-entry-exit"`) and `animate-to-from-top-layer` (via `npx -y modern-web-guidance@latest retrieve "animate-to-from-top-layer"`).
@@ -17,61 +17,54 @@
display,
overlay;
transition-duration: 0.2s;
+ /* Separate after transition so the shorthand doesn't reset it or fail in older browsers */
transition-behavior: allow-discrete;
}
```
-### Accessibility
+## Accessibility
-Use `prefers-reduced-motion` media queries to turn off heavy motion for users who prefer it.
-- **Provide Pause mechanism**: Allow users to stop auto-running carousels, banners, or other persistent animations.
-- **Default to static views**: Consider defaulting to static states and allowing users to opt-in to motion.
-- **Don't exceed flash limits (three per second)**: Never include rapid light-to-dark flashing. Such effects can cause seizures.
+- **Provide a pause mechanism**: Allow users to stop auto-running carousels, banners, or other persistent animations. Any moving, blinking, or scrolling content that starts automatically, lasts more than five seconds, and is shown alongside other content needs a visible control to pause, stop, or hide it, such as a `<button>` next to the content that works with the keyboard (WCAG 2.2.2 Pause, Stop, Hide). `prefers-reduced-motion` doesn't replace the control, because users who haven't turned on that setting still need to stop the motion. If the button's label changes between "Pause" and "Play", don't also set `aria-pressed`, or screen readers announce a pressed "Play" button.
+- **Default to static views**: Consider defaulting to static states and allowing users to opt in to motion.
+- **Don't exceed flash limits (three per second)**: Never include rapid light-to-dark flashing. Such effects can cause seizures. This applies whatever the user's motion preference, so don't put flashing content inside `@media (prefers-reduced-motion: no-preference)` either (WCAG 2.3.1 Three Flashes or Below Threshold: nothing flashes more than three times in any one-second period).
+- **Keep the final state**: When you turn off an animation, make sure the element still ends in its final state, so content isn't left hidden (for example, at `opacity: 0`) and focus and selection indicators still appear.
-**DO NOT** globally apply `animation-duration: 0.01ms;` as it can cause certain animations to become _more_ jarring.
-Instead, handle motion preferences on a case-by-case basis using one of two approaches, nesting the `@media` query inside the rule so both versions are kept together:
+### Respect reduced motion
-- **Start with animations enabled by default, and tone them down using `@media (prefers-reduced-motion: reduce)`**:
+Always respect reduced motion preferences. Choose between `@media (prefers-reduced-motion: no-preference)` and `@media (prefers-reduced-motion: reduce)` based on whether reduced motion removes the animation entirely or only adjusts its parameters:
+- Use `@media (prefers-reduced-motion: no-preference)` when the reduced-motion strategy is to **not have the animation at all** (apply the animation only where needed rather than declaring it broadly and canceling it with `animation: none`).
+- Use `@media (prefers-reduced-motion: reduce)` when the reduced-motion strategy is to **change animation parameters** (such as slowing down `animation-duration`).
-```css
-/* Good: Dampen spin states or slow down animations for reduced motion */
-.spinner {
- animation: spin 1s linear infinite;
- @media (prefers-reduced-motion: reduce) {
- animation: none;
- opacity: 0.5;
- }
-}
+**DO NOT** globally apply `animation-duration: 0.01ms;` as it can cause certain animations to become _more_ jarring. Instead, handle reduced motion on a case-by-case basis by nesting the `@media` query inside the rule so both versions are kept together. Keep non-motion transitions (such as `color` or `background-color` changes on links and buttons) enabled; only dampen or disable spatial movement, scaling, rotation, or persistent animations.
-progress:not([value]) {
- animation: slide 1s infinite linear;
- @media (prefers-reduced-motion: reduce) {
- animation-duration: 20s;
- }
-}
-```
+#### Opt in to motion with `@media (prefers-reduced-motion: no-preference)`
-- **Start with no animations by default, and enable them using `@media (prefers-reduced-motion: no-preference)`**:
+When reduced motion should have no animation at all, default to the static state and enable the animation inside `@media (prefers-reduced-motion: no-preference)` instead of setting `animation` and overriding it with `animation: none`:
```css
-/* Good: Default to static or gentle states and opt-in to full motion */
+/* Good: Default to static state and opt in to full motion */
.spinner {
- opacity: 0.5;
@media (prefers-reduced-motion: no-preference) {
- opacity: 1;
animation: spin 1s linear infinite;
}
}
+```
+
+#### Adjust animation parameters with `@media (prefers-reduced-motion: reduce)`
+When the animation should still run under reduced motion with gentler parameters, declare the base animation and override only the changed properties inside `@media (prefers-reduced-motion: reduce)`:
+
+```css
+/* Good: Slow down the animation for reduced motion instead of canceling it */
progress:not([value]) {
- animation: slide 20s infinite linear;
- @media (prefers-reduced-motion: no-preference) {
- animation-duration: 1s;
+ animation: slide 1s infinite linear;
+ @media (prefers-reduced-motion: reduce) {
+ animation-duration: 20s;
}
}
```
-### Working with animation and transition events in JavaScript
+## Working with animation and transition events in JavaScript
On both the `AnimationEvent` (`animationstart`, `animationiteration`, `animationend`, `animationcancel`) and `TransitionEvent` (`transitionrun`, `transitionstart`, `transitionend`, `transitioncancel`) interfaces, `event.target` gives you the originating DOM element. To access the specific `Animation` object (`Animation`, `CSSAnimation`, or `CSSTransition`) that triggered the event, use the readonly `event.animation` property.
@@ -99,4 +92,6 @@ document.addEventListener('animationstart', (event) => {
});
```
-You can feature-detect support using `'animation' in AnimationEvent.prototype` (or `'animation' in TransitionEvent.prototype`).
\ No newline at end of file
+You can feature-detect support using `'animation' in AnimationEvent.prototype` (or `'animation' in TransitionEvent.prototype`).
+
+When reduced motion means an animation or transition never runs (it's only applied inside `@media (prefers-reduced-motion: no-preference)`, set to `none`, or given a zero duration and no delay), `animationend` and `transitionend` never fire. If your code waits for these events to remove or hide an element, continue immediately when `element.getAnimations()` returns an empty array, or keep a short opacity transition instead of removing it.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/move-dom-element-without-losing-state.md b/skills/modern-web-guidance/guides/ui-behaviors/move-dom-element-without-losing-state.md
index f3739fe..7c47351 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/move-dom-element-without-losing-state.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/move-dom-element-without-losing-state.md
@@ -4,7 +4,7 @@ When reparenting DOM elements using traditional methods like `appendChild()` or
To move an element while preserving its state, use the `moveBefore()` API. This method performs an atomic move, completely bypassing the removal and insertion steps.
-### Moving an element with state
+## Moving an element with state
Use `moveBefore()` exactly as you would use `insertBefore()`. It requires two arguments: the node to move, and a reference node to insert before (or `null` to append to the end of the new parent).
@@ -17,7 +17,7 @@ const elementWithState = document.getElementById('iframe-or-focused-input');
newParent.moveBefore(elementWithState, null);
```
-### Moving custom elements (Web Components)
+## Moving custom elements (Web Components)
If you are moving custom elements using `moveBefore()`, their `connectedCallback` and `disconnectedCallback` lifecycle methods will **not** be fired.
@@ -36,13 +36,13 @@ class MyCustomElement extends HTMLElement {
}
```
-### Fallback strategies
+## Fallback strategies
Browser support for moveBefore(): Limited availability.
Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), and Firefox 144 (Oct 2025).
Unsupported in: Safari.
-Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it, falling back to traditional `insertBefore()` or `appendChild()` operations for older browsers.
+Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it, falling back to traditional `insertBefore()` or `appendChild()` operations for older browsers.
```javascript
const targetParent = document.getElementById('target-container');
@@ -56,4 +56,14 @@ if ('moveBefore' in Element.prototype) {
// Note: This WILL reset <iframe>, animation, and focus state in unsupported browsers.
targetParent.insertBefore(nodeToMove, null);
}
-```
\ No newline at end of file
+```
+
+## Accessibility considerations
+
+Make sure that moving or reparenting an element does not cause any potentially disorienting changes of context, such as a loss of keyboard focus to the page's `<body>` element.
+
+Where possible, make sure that the change is triggered by the user, rather than an automatic change, to prevent unexpected changes of context.
+
+Make sure that moving or reparenting an element does not affect the meaning of the overall content. For example, if a page contains several panels of content that can be, or are intended to be, read independently and in any order, the meaning of the overall content is not affected through repositioning. However, if these panels of content must be presented in a certain sequence in order to be understood, repositioning the content in the DOM can break the reading sequence even if the visual order still makes sense. This can disorient people who cannot see the content and who use a screen reader.
+
+If moving or reparenting an element triggers a change that is important for people to know about, for example moving a video from one area of the page to a "Favorites" list in another area of the page, use a live region to confirm that the move was was successful.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/parallax-scroll-effects.md b/skills/modern-web-guidance/guides/ui-behaviors/parallax-scroll-effects.md
index 3ec8e01..6a0175d 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/parallax-scroll-effects.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/parallax-scroll-effects.md
@@ -57,6 +57,8 @@ Here’s how to create a basic parallax effect:
5. **Stagger the animations:** To make the layers move at different speeds, you can use one of two main approaches: **staggering in the keyframes**, or **staggering the `animation-range`**.
+ Choose **staggering in the keyframes** when layers share a common animation timeline and range but require distinct travel distances (simplest for a fixed number of layers). Choose **staggering the `animation-range`** when layers should enter and exit at different scroll thresholds across a long container.
+
Both of these approaches can use hardcoded values, or can use the `sibling-index()`/`sibling-count()` implementation. The hardcoded values are easiest and also useful when having only a limited amount of layers. The `sibling-index()`/`sibling-count()` implementation is handy when you have many layers.
* **Staggering in the keyframes:**
@@ -174,9 +176,8 @@ As for setting the `animation-range`:
## Browser support and fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.. Therefore, a fallback strategy is typically required.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).. Therefore, a fallback strategy is typically required.
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
@@ -184,11 +185,13 @@ In browsers with built-in support for scroll-driven animations, ALWAYS use the n
Note that not every effect can be recreated using the fallbacks approach.
-For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.
+For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position. The `prefers-reduced-motion` media query in the CSS doesn't affect the inline styles the script sets, so the script checks the preference with `matchMedia()` and doesn't run when the user prefers reduced motion.
```js
// Fallback for browsers that don't support scroll-driven animations
-if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {
+// Like the CSS, it doesn't run when the user prefers reduced motion.
+if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)') &&
+ !matchMedia('(prefers-reduced-motion: reduce)').matches) {
const wrapper = document.querySelector('.wrapper');
const layers = document.querySelectorAll('.layer');
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scroll-completion-effects.md b/skills/modern-web-guidance/guides/ui-behaviors/scroll-completion-effects.md
index 3c1ff74..b501a5e 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/scroll-completion-effects.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scroll-completion-effects.md
@@ -48,6 +48,12 @@ targetHeading.focus({ preventScroll: true });
- **DO**: Guard post-scroll effects with a request token if rapid user interactions can trigger overlapping smooth scrolls on the same container, since interrupting a smooth scroll resolves (rather than rejects) the previous promise.
- **Known Chrome bug with the root scroller**: Chrome has a bug where the `Promise` returned by `scrollIntoView()` resolves too early when it is the document's root scroller that is scrolling. Awaiting a `scrollIntoView()` on a nested scroll container works as expected. Do not wrap your content in a scroll container, such as `div` with `overflow-y: auto`, as a workaround for this bug.
+## Accessibility considerations
+
+Ensure that the control used to trigger scrolling has an appropriate role. If the scrolling is intended to redirect the user elsewhere in the current context, then use a `<a>` element with a `href` attribute, so that it receives an implicit `link` role, along with the expected keyboard interactions. Redirect focus to this location scrolled to, so that people can continue navigating from the location that they are redirected to.
+
+**DON'T** provide important information solely through visual design updates upon completion of programmatic scrolling. If there is important information that needs to be conveyed as a result of this interaction, ensure that this is available in sufficiently contrasting text, and that this is conveyed to people using screen readers through use of an ARIA live region.
+
## Fallback strategies
Browser support for Scroll method promises: Limited availability.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scroll-entry-exit-effects.md b/skills/modern-web-guidance/guides/ui-behaviors/scroll-entry-exit-effects.md
index 67b74d3..1d32304 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/scroll-entry-exit-effects.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scroll-entry-exit-effects.md
@@ -25,8 +25,8 @@ To add entry and exit effects to an element, you need to combine a few CSS prope
```css
.animated-element {
animation:
- slide-in 1s linear backwards,
- slide-out 1s linear forwards;
+ slide-in auto linear backwards,
+ slide-out auto linear forwards;
}
```
@@ -51,6 +51,8 @@ To add entry and exit effects to an element, you need to combine a few CSS prope
}
```
+ Alternatively, instead of defining two separate `@keyframes` rules and setting `animation-range: entry, exit`, you can centralize both phases in a **single `@keyframes` block** using `<timeline-range-name>` selectors (`entry 0%`, `entry 100%`, `exit 0%`, `exit 100%`) with `animation-fill-mode: both`. Use separate `@keyframes` when reusing and composing standalone animations (such as shared `fade-in` and `fade-out` keyframes), or a single `@keyframes` rule when keeping an element's entry and exit logic centralized in one place.
+
## Example code
This code animates the direct children of the scroller on scroll using an **anonymous view-timeline**:
@@ -82,7 +84,7 @@ This code animates the direct children of the scroller on scroll using an **anon
As the elements enter the scrollport the `grow` animation is played, and as they leave the scrollport the `shrink` animation is played.
-The following code has the same visual outcome, but animates the direct children of the scroller on scroll using an **named view-timeline**:
+The following code has the same visual outcome, but animates the direct children of the scroller on scroll using a **named view-timeline**:
```css
@media (prefers-reduced-motion: no-preference) {
@@ -110,6 +112,33 @@ The following code has the same visual outcome, but animates the direct children
}
```
+You can also express the same entry and exit effect in a **single `@keyframes` rule** using timeline-range selectors (with `both` fill mode and no `animation-range` override needed on the element):
+
+```css
+@media (prefers-reduced-motion: no-preference) {
+ @supports ((animation-timeline: view()) and (animation-range: entry)) {
+ @keyframes grow-and-shrink {
+ entry 0% {
+ scale: 0.5; /* Example value */
+ }
+ /* Explicitly set the resting state across the middle (`contain`) phase so the element doesn't interpolate straight from entry 0% to exit 100% */
+ entry 100%,
+ exit 0% {
+ scale: 1;
+ }
+ exit 100% {
+ scale: 0.5;
+ }
+ }
+
+ .scroller > * {
+ animation: grow-and-shrink auto linear both;
+ animation-timeline: view(inline);
+ }
+ }
+}
+```
+
## Best Practices
When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:
@@ -120,12 +149,13 @@ When using scroll-driven animations, it's important to follow a few best practic
- If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.
- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.
- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.
-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.
+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting them.
+
+Use an anonymous `view()` timeline by default when the animated element is the same element being tracked, so you do not have to name every individual timeline. Use a named `view-timeline` instead when multiple elements reuse a single timeline (avoiding duplicate timelines) or when reaching across the DOM (such as animating descendants or non-ancestors via `timeline-scope` when `view()` or `scroll(nearest)` does not suffice).
When using the `view()` function to create a scroll-driven animation:
- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view(block)` or `view(inline)`.
-- When the animation is not applied to the tracked subject itself, use a named view timeline.
When using the `view-timeline` property to create a scroll-driven animation:
@@ -133,13 +163,12 @@ When using the `view-timeline` property to create a scroll-driven animation:
- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.
- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.
-Prefer a named `view-timeline` when multiple elements or children of the tracked subject need to animate.
-
## Browser support and fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.. Therefore, a fallback strategy is typically required.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Therefore, a fallback strategy is typically required.
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
@@ -147,11 +176,13 @@ In browsers with built-in support for scroll-driven animations, ALWAYS use the n
Note that not every effect can be recreated using the fallbacks approach.
-For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.
+For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of each `.scroller > *` element and updates its `scale` property based on `intersectionRatio`. The `prefers-reduced-motion` media query in the CSS doesn't affect the inline styles the script sets, so the script checks the preference with `matchMedia()` and only runs when the user has no reduced-motion preference.
```html
<script>
- if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {
+ // Like the CSS, the fallback only runs when the user has no reduced-motion preference.
+ if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)') &&
+ matchMedia('(prefers-reduced-motion: no-preference)').matches) {
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-realtime-feedback.md b/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-realtime-feedback.md
index f5ee403..00b4d27 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-realtime-feedback.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-realtime-feedback.md
@@ -94,7 +94,20 @@ if (document.readyState === 'complete') {
}
```
-### Fallback strategies
+## Accessibility considerations
+
+If creating a carousel or gallery pattern, which has associated controls for navigation:
+
+1. Ensure that parity is maintained between the controls that relate to the scroll container, and the content displayed in the scroll container. The correct state of the associated controls must be updated (using `aria-current="true"`) as the scroll container updates, so that people can determine the current content.
+2. Wrap the entire component in a `<section>` element, with an accessible name. Give the element a `focusgroup="toolbar wrap"` property, updating the value to match the visual design used. This will manage focus and provide a roving tabindex behaviour for the controls.
+3. Ensure that the name for the button matches the text/description in the scroll-container that it controls. This way, people reading through the content can understand the relationship between the control and the content it displays.
+
+> [!NOTE]
+> This pattern does not represent a traditional carousel component in which slides typically automatically change, in a way that doesn't allow people to pause or stop the transition, or accurately communicate the visible information to people using screen readers. If the intended use case is a carousel that only presents a single slide at any time and automatically transitions between slides, then do not use this technique, as it lacks the accessibility information required for such a component. Instead, opt for a tab-like implementation, ensuring that the carousel can be operated using a keyboard alone, that the carousel can be paused or stopped, and that the semantic information including the name, role, and state, is accurately conveyed to people using screen readers. Making carousel components accessible to everyone is highly nuanced and context-dependent; be sure to refer to established accessibility standards and perform thorough user testing for production environments.
+
+To ensure consistent operability across different browsers and assistive technology combinations, ensure that the scrollable container can receive focus (by applying `tabindex="0"`), and has an accessible name that describes the content, along with an appropriate role (such as `role="region"`).
+
+## Fallback strategies
Browser support for Scroll snap events: Limited availability.
Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
Unsupported in: Firefox and Safari.
@@ -154,3 +167,53 @@ if ('onscrollsnapchanging' in Element.prototype) {
```
The geometric `scroll` + `requestAnimationFrame` fallback closely emulates the behavior of native snap prediction, including handling programmatic scrolling correctly. Because functions like `scrollIntoView` naturally fire `scroll` events during their execution, the UI will stay smoothly synchronized throughout the scroll animation without requiring additional custom logic.
+
+### Fallbacks & browser support for focusgroup
+
+Browser support for focusgroup: Limited availability.
+Supported by: Chrome 150 (Jun 2026) and Edge 150 (Jul 2026).
+Unsupported in: Firefox and Safari.
+
+Keep `focusgroup="toolbar wrap"` in the markup. If `'focusGroup' in HTMLElement.prototype` is false, implement a roving tabindex pattern on the gallery controls, and manually apply a `role="toolbar"` to the container. Never install it when native focusgroup is present.
+
+```js
+if (!('focusGroup' in HTMLElement.prototype)) {
+ document.querySelectorAll('[focusgroup~="toolbar"]').forEach(group => {
+ group.setAttribute('role', 'toolbar');
+
+ const items = () => [...group.querySelectorAll('button')]
+ .filter(item => item.closest('[focusgroup]') === group)
+ .filter(item => !item.disabled && item.getAttribute('aria-disabled') !== 'true');
+
+ const syncTabIndex = () => {
+ const list = items();
+ let current = list.indexOf(document.activeElement);
+
+ if (current < 0) {
+ current = list.indexOf(list.find(item => item.getAttribute('aria-current') === 'true'));
+ }
+
+ list.forEach((item, index) => {
+ item.tabIndex = current === index ? 0 : -1;
+ });
+ };
+
+ group.addEventListener('focusin', syncTabIndex);
+ group.addEventListener('keydown', event => {
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
+ const list = items();
+ const current = list.indexOf(document.activeElement);
+ if (current < 0) return;
+ const next = (current + (event.key === 'ArrowLeft' ? -1 : 1) + list.length) % list.length;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ list.forEach((item, index) => {
+ item.tabIndex = index === next ? 0 : -1;
+ });
+ list[next].focus({ preventScroll: true });
+ }, true);
+
+ syncTabIndex();
+ });
+}
+```
\ No newline at end of file
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-state-sync.md b/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-state-sync.md
index e9dd92b..3d011e2 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-state-sync.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-state-sync.md
@@ -48,7 +48,6 @@ main.addEventListener('scrollsnapchange', (event) => {
});
```
-
## Accessibility
Caution: While Scroll Snap Events make it possible to visually synchronize other content to the state of the scroller, it does not automatically expose that information programmatically. Relationships between elements, active states, and live content must be reflected in the Accessibility Tree.
@@ -57,6 +56,16 @@ For a table of contents, ensure the sidebar links use `aria-current="true"` or `
In addition, be careful when using the `mandatory` value for `scroll-snap-type`, as it can cause content in-between snap-points to become inaccessible when longer than the screen.
+To ensure that people can navigate the scrollable region after selecting an anchor element, apply the corresponding element with a `tabindex="-1"` attribute. This will allow the element to receive focus, and allow people using a keyboard to scroll the container, or easily navigate from that content.
+
+```html
+<li><a href="#section-2">Section 2</a></li>
+…
+<!-- Adding a tabindex="-1" attribute to the heading will mean that it can receive focus after being navigated to -->
+<h2 id="section-2" tabindex="-1">Section 2</h2>
+```
+
+To ensure consistent operability across different browsers and assistive technology combinations, ensure that the scrollable container can receive focus (by applying `tabindex="0"`), and has an accessible name that describes the content, along with an appropriate role (such as `role="region"`), if it does not already have an implicit role (which elements like `<main>` do).
## Fallback strategies
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md b/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md
index 9c4f909..afc40ce 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md
@@ -54,38 +54,40 @@ Finally, you can use the `animation-range` property to specify the exact range o
## Example code
```css
-html {
- timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;
-}
-
-#tracked {
- section:nth-child(1){ view-timeline: --tl-1 block; }
- section:nth-child(2){ view-timeline: --tl-2 block; }
- section:nth-child(3){ view-timeline: --tl-3 block; }
- section:nth-child(4){ view-timeline: --tl-4 block; }
- section:nth-child(5){ view-timeline: --tl-5 block; }
-}
+@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%)) {
+ html {
+ timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;
+ }
-@keyframes animate-in {
- from { scale: 0.5; opacity: 0; transform: rotateY(-180deg); }
- to { transform: rotateY(0deg); }
-}
-@keyframes animate-out {
- to { translate: 100% 0; opacity: 0; }
-}
+ #tracked {
+ section:nth-child(1){ view-timeline: --tl-1 block; }
+ section:nth-child(2){ view-timeline: --tl-2 block; }
+ section:nth-child(3){ view-timeline: --tl-3 block; }
+ section:nth-child(4){ view-timeline: --tl-4 block; }
+ section:nth-child(5){ view-timeline: --tl-5 block; }
+ }
-#animated {
- section {
- animation: animate-in auto linear both, animate-out auto linear forwards;
- animation-range: entry 25% cover 50%, exit 50% exit 75%;
- backface-visibility: hidden;
+ @keyframes animate-in {
+ from { scale: 0.5; opacity: 0; transform: rotateY(-180deg); }
+ to { transform: rotateY(0deg); }
+ }
+ @keyframes animate-out {
+ to { translate: 100% 0; opacity: 0; }
}
- section:nth-child(1){ animation-timeline: --tl-1; }
- section:nth-child(2){ animation-timeline: --tl-2; }
- section:nth-child(3){ animation-timeline: --tl-3; }
- section:nth-child(4){ animation-timeline: --tl-4; }
- section:nth-child(5){ animation-timeline: --tl-5; }
+ #animated {
+ section {
+ animation: animate-in auto linear both, animate-out auto linear forwards;
+ animation-range: entry 25% cover 50%, exit 50% exit 75%;
+ backface-visibility: hidden;
+ }
+
+ section:nth-child(1){ animation-timeline: --tl-1; }
+ section:nth-child(2){ animation-timeline: --tl-2; }
+ section:nth-child(3){ animation-timeline: --tl-3; }
+ section:nth-child(4){ animation-timeline: --tl-4; }
+ section:nth-child(5){ animation-timeline: --tl-5; }
+ }
}
/* MANDATORY Copy-Paste Safety: Disable continuous storytelling motion for sensitive users */
@@ -118,9 +120,8 @@ When using the `view-timeline` property to create a scroll-driven animation:
## Fallback strategies
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).
@@ -132,13 +133,16 @@ For this use-case specifically, the following script applies the fallback for br
```js
const animatedSections = document.querySelectorAll('#animated section');
+// The CSS only hides the sections once this class is set, so they stay visible if the script doesn't run
+document.querySelector('#animated').classList.add('scroll-fallback');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const sectionIndex = Array.from(document.querySelectorAll('#tracked section')).indexOf(entry.target);
if (sectionIndex !== -1) {
const animatedSection = animatedSections[sectionIndex];
- const ratio = entry.intersectionRatio;
+ // Reaches 1 once the section fills the viewport, even when it's taller than the viewport
+ const ratio = Math.min(1, entry.intersectionRect.height / Math.min(entry.boundingClientRect.height, innerHeight));
// Animate-in
animatedSection.style.opacity = ratio;
@@ -162,7 +166,7 @@ document.querySelectorAll('#tracked section').forEach(section => {
And the accompanying CSS:
```css
-#animated section {
+#animated.scroll-fallback section {
opacity: 0;
transform: scale(0.5) rotateY(-180deg);
backface-visibility: hidden;
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/sortable-table.md b/skills/modern-web-guidance/guides/ui-behaviors/sortable-table.md
new file mode 100644
index 0000000..0c96703
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/sortable-table.md
@@ -0,0 +1,140 @@
+# Sortable Table
+
+Use this pattern to let users sort a data table by clicking its column headers. Start from a complete, semantic `<table>` that is readable without JavaScript, then enhance it.
+
+This guide covers the header controls, sort state, sorting logic, and applying the new order to the DOM. For keeping state inside rows while they move, see `move-dom-element-without-losing-state` (via `npx -y modern-web-guidance@latest retrieve "move-dom-element-without-losing-state"`). For other narrow-screen table patterns, see `responsive-table` (via `npx -y modern-web-guidance@latest retrieve "responsive-table"`).
+
+For sorting lists and card grids that are not tables, see `dynamic-sort` (via `npx -y modern-web-guidance@latest retrieve "dynamic-sort"`).
+
+## Header markup
+
+* **MANDATORY:** Put a `<button type="button">` inside each sortable `<th scope="col">`. Do not make the `<th>` itself clickable, and do not use `<a>` or `role="button"`.
+* Set `aria-sort="ascending"` or `aria-sort="descending"` on the `<th>` of the currently sorted column only, and remove it from all other headers. Do not set `aria-sort="none"`, and do not put `aria-sort` on the button.
+* Leave non-sortable columns as plain `<th>` text with no button. Keep their padding, alignment and font weight matching the sortable headers: drop the cell padding only on `th:has(> button)`, since the button supplies it.
+* Keep the table's `<caption>` as its accessible name, and keep data rows in a `<tbody>` so sorting reorders only body rows and never the `<thead>` row.
+* Use a decorative icon for the sort direction (`aria-hidden="true"`, `currentColor`, see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`)). Drive its appearance from `th[aria-sort]` in CSS, not from extra classes or JavaScript. The icon is visual only and hidden from assistive technology, so always convey the sort state with `aria-sort` on the `<th>`.
+* Give the button a minimum 24px target and a `:focus-visible` outline. Make it fill the cell.
+
+## Wire buttons with invoker commands
+
+Use `commandfor` pointing at the table and a custom `--sort` command (custom commands must start with `--`). Handle it with one `command` listener on the table instead of a click listener per button. `event.source` is the button that was activated.
+
+```html
+<th scope="col" data-type="number">
+ <button type="button" commandfor="planets" command="--sort">
+ Moons
+ </button>
+</th>
+```
+
+```javascript
+table.addEventListener('command', (event) => {
+ if (event.command !== '--sort') return;
+
+ const th = event.source.closest('th');
+ const direction = th.getAttribute('aria-sort') === 'ascending' ? 'descending' : 'ascending';
+
+ for (const header of table.tHead.rows[0].cells) header.removeAttribute('aria-sort');
+ th.setAttribute('aria-sort', direction);
+
+ const rows = sortRows([...tbody.rows], th.cellIndex, th.dataset.type, direction);
+ reorderWithTransition(rows);
+ // One message per sort; the status element must already be in the DOM.
+ status.textContent = `Sorted by ${event.source.textContent.trim()}, ${direction}, ${rows.length} rows`;
+});
+```
+
+* The first activation sorts ascending; each repeat toggles direction. Switching columns starts ascending again.
+* Keep focus on the header button that was activated.
+
+## Compare values correctly
+
+* Compare text with `Intl.Collator` (`numeric: true, sensitivity: 'base'`), not `<` or `localeCompare` in a loop.
+* Compare numbers, dates and currency as numbers. Read the raw value from a `data-value` attribute (or `<time datetime>`) when the displayed text is formatted, for example `12,104` or `$1.2k`.
+* Declare the type per column with `data-type` rather than guessing from content.
+* `Array.prototype.sort` is stable, so equal rows keep their previous relative order.
+
+```javascript
+const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
+
+function sortRows(rows, index, type, direction) {
+ const factor = direction === 'ascending' ? 1 : -1;
+ // Prefer the raw value when the displayed text is formatted.
+ // This reads the DOM on every comparison; for large tables, read each row's value once before sorting.
+ const value = (row) => row.cells[index].dataset.value ?? row.cells[index].textContent.trim();
+ return rows.sort((a, b) =>
+ factor * (type === 'number' ? value(a) - value(b) : collator.compare(value(a), value(b)))
+ );
+}
+```
+
+## Reorder the existing rows
+
+**MANDATORY:** Move the existing `<tr>` elements within the `<tbody>`. Do not rebuild the table or `<tbody>` with `innerHTML` or a re-render: that discards focus and state inside rows and breaks view transitions, which match old and new elements by identity. Never move the header row.
+
+```javascript
+// Moving every row to the end in sorted order is enough; no need to compute minimal moves.
+function reorder(container, orderedRows) {
+ for (const row of orderedRows) container.moveBefore(row, null);
+}
+```
+
+**DO NOT** fake the order with CSS `order`; DOM order must match visual order for keyboard and screen reader users.
+
+## Optionally animate the reorder
+
+Animation is an enhancement; the sort works without it. For when to animate, reduced-motion handling and rapid-click behavior, see `dynamic-sort` (via `npx -y modern-web-guidance@latest retrieve "dynamic-sort"`). Skip it for large tables.
+
+```css
+tbody tr {
+ /* Derives a unique name from each row's identity. */
+ view-transition-name: match-element;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ ::view-transition-group(*),
+ ::view-transition-old(*),
+ ::view-transition-new(*) {
+ animation: none;
+ }
+}
+```
+
+```javascript
+// Scoped to the table so the rest of the page stays interactive during the animation.
+function reorderWithTransition(rows) {
+ table.startViewTransition(() => reorder(tbody, rows));
+}
+```
+
+* **DO NOT** put `aria-live` on the table: it would announce every moved row. Use the single `role="status"` element instead, hidden visually (not with `display: none`) using `clip-path: inset(50%)` and a 1px size.
+
+## Narrow screens
+
+Wrap the table in a horizontally scrollable container (`overflow-x: auto`) with `role="region"`, an accessible name from the caption via `aria-labelledby`, and `tabindex="0"` so keyboard users can scroll it. Give the table a `min-inline-size` so columns do not collapse.
+
+## Common mistakes
+
+* **DO NOT** re-render the `<tbody>` or `<table>` on sort; it discards focus and state and breaks view transitions.
+* **DO NOT** put `aria-live` on the table, or announce each row.
+* **DO NOT** leave `aria-sort` on more than one header.
+* **DO NOT** change the button's label to describe the action ("Sort ascending"). Keep the column name; `aria-sort` conveys state.
+* **DO NOT** sort formatted strings when the underlying values are numbers or dates.
+
+## Fallbacks
+
+Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
+Supported by: Chrome 135 (Apr 2025), Edge 135 (Apr 2025), Firefox 144 (Oct 2025), and Safari 26.2 (Dec 2025).
+
+If your Baseline target does not support invoker commands, add a `click` listener to each header button that runs the same sort function. Behavior is identical. The buttons do nothing without JavaScript either way, so add them from script if the table must stay fully readable without it.
+
+Browser support for Element-scoped view transitions: Limited availability.
+Supported by: Chrome 147 (Apr 2026) and Edge 147 (Apr 2026).
+Unsupported in: Firefox and Safari.
+
+Browser support for moveBefore(): Limited availability.
+Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), and Firefox 144 (Oct 2025).
+Unsupported in: Safari.
+
+If your Baseline target does not support `moveBefore()` or element-scoped view transitions, follow the fallbacks in `dynamic-sort` (via `npx -y modern-web-guidance@latest retrieve "dynamic-sort"`); the table still sorts and the announcement is unchanged.
+
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md b/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md
index 9bab3dd..38c9dd4 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md
@@ -10,7 +10,7 @@ This guide covers building performant, accessible 2D directional navigation insi
When implementing custom arrow-key spatial focus, adhere to these foundational rules:
-1. **Limit to composite widgets**: Do not override arrow keys on normal document text flow or simple vertical list layouts where default sequential Tab navigation is expected. See `accessibility` (via `npx -y modern-web-guidance@latest retrieve "accessibility"`) for general document flow guidance.
+1. **Limit to composite widgets**: Do not override arrow keys on normal document text flow or simple vertical list layouts where default sequential Tab navigation is expected. It must only be used if there is an appropriate composite role that matches the interaction. See `accessibility` (via `npx -y modern-web-guidance@latest retrieve "accessibility"`) for general document flow guidance.
2. **Preserve native boundary scrolling**: If there is no focusable element in the pressed direction, **do not prevent default browser behavior**. Let the event bubble so the browser can scroll the viewport natively. Overriding arrow keys unconditionally breaks accessibility (WCAG 1.4.10).
3. **Ensure focus visibility and alignment**: When focus changes, ensure the newly focused element is scrolled into view (e.g., using `scrollIntoView({ block: 'nearest', inline: 'nearest' })`) so that it remains fully visible.
4. **Coordinate with the layout system**: Determine focus candidate positions from live bounding geometries (`getBoundingClientRect()`) while handling each keypress. Avoid assuming that DOM order or a fixed grid structure represents the visual layout. See `css-layout` (via `npx -y modern-web-guidance@latest retrieve "css-layout"`) for modern layout recommendations.
@@ -24,6 +24,15 @@ The spatial container must expose a single tab stop to sequential Page Tab navig
* All inactive items have `tabindex="-1"`.
* When navigating, programmatically move focus by shifting the `tabindex="0"` attribute and calling `focus()`.
+Roving tabindex only works with screen readers when the container and items have appropriate composite-widget roles and states (e.g. grid/gridcell, listbox/option); tabindex alone isn't enough.
+
+- If the spatial navigation is used to navigate through rows of interactive elements, then use `grid` semantics
+- If the spatial navigation is used to navigate through multiple interactive elements, which when selected, update the content related to the selected control, then use `tablist` semantics
+- If the spatial navigation is a list of suggested items, which upon selected, populate a related input field, then use `combobox` semantics
+- If the spatial navigation is used to navigate a list, for which one or more option is selectable, then use `listbox` semantics
+- If the spatial navigation is used to navigate a collection of interactive items with a clear hierarchy, then use `tree` semantics
+- If the spatial navigation is used to navigate a grid-like pattern, with expandable items, and a clear hierarchy, then use `treegrid` semantics
+
---
### Visual Candidate Selection
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md b/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md
index 97f2196..2a6fcf5 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md
@@ -13,19 +13,35 @@ The component has two layers: a **list** (the `<ul>`) and the **items** inside i
### Step 1: Mark up the list with track and content
```html
-<ul class="SwipeableList">
+<!-- tabindex="-1" lets focus move here when the last item is removed (Step 4). -->
+<h2 id="list-heading" tabindex="-1">Inbox</h2>
+
+<!-- Safari removes list semantics when list-style is none; role="list"
+ restores the item count for screen readers. -->
+<ul class="SwipeableList" role="list" aria-labelledby="list-heading">
<li id="list-item-1" class="SwipeableList-item">
<div class="SwipeableList-track">
- <div class="SwipeableList-content">Item One</div>
- </div>
- </li>
- <li id="list-item-2" class="SwipeableList-item">
- <div class="SwipeableList-track">
- <div class="SwipeableList-content">Item Two</div>
+ <div class="SwipeableList-content">
+ <span class="SwipeableList-label">Item One</span>
+ <!-- Swiping can't be done with a keyboard, a single tap or a screen
+ reader, so each swipe action needs another way to run it (see
+ "Accessibility considerations"). This example gives each swipe
+ action its own button. data-direction
+ is the swipe direction the button stands in for (Step 4), and
+ including the item name in the button text tells screen reader
+ users which row it acts on. This example has a single action. -->
+ <button type="button" class="SwipeableList-action" data-direction="right">
+ Remove<span class="visually-hidden"> Item One</span>
+ </button>
+ </div>
</div>
</li>
<!-- ...more items... -->
</ul>
+
+<!-- Screen readers only announce changes to a live region that was already
+ in the page, so render this empty and fill it on removal (Step 4). -->
+<p role="status" class="SwipeableList-status visually-hidden"></p>
```
### Step 2: Configure the track as a horizontal snap container with three snap points
@@ -62,7 +78,8 @@ The track configuration is gated behind an `.is-initialized` class on the list i
back-gesture on iOS/Android. */
overscroll-behavior-x: none;
- /* Hide the scrollbar; the gesture is the affordance. */
+ /* Hide the scrollbar; the swipe doesn't need one, and the action
+ buttons (Step 1) are the visible alternative. */
scrollbar-width: none;
/* `mandatory` ensures the track always rests on a snap point
@@ -199,6 +216,25 @@ The placement, sizing, and motion below are a **starting suggestion**, not a req
.SwipeableList-item.is-activating[data-swipe-direction="right"]::before {
visibility: hidden;
}
+
+/* Skip the icon pop for users who prefer reduced motion. */
+@media (prefers-reduced-motion: reduce) {
+ .SwipeableList-item.is-activating::before,
+ .SwipeableList-item.is-activating::after {
+ scale: 1;
+ }
+}
+
+/* Forced colors replaces the action background with Canvas, which hides the
+ white icon. Paint the icon shape in CanvasText instead so it stays visible. */
+@media (forced-colors: active) {
+ .SwipeableList-item.is-initialized::before,
+ .SwipeableList-item.is-initialized::after {
+ forced-color-adjust: none;
+ background: CanvasText;
+ mask: var(--action-icon) center / contain no-repeat;
+ }
+}
```
### Step 4: Detect the commit gesture with `IntersectionObserver`
@@ -208,10 +244,11 @@ Use `IntersectionObserver` rooted at the track, observing the content. As the us
- `activateThreshold`: a high ratio (e.g., 0.8). When the visible portion of the content drops below this, the user is past the visual activate point. Toggle the icon-pop affordance.
- `commitThreshold`: a low ratio (e.g., 0.2). When the visible portion drops below this, the user has committed. Start the remove animation **immediately**, without waiting for the snap gesture to fully settle. The collapsing row blends into the user's continuing swipe momentum, which feels more responsive than waiting for the snap to land before reacting.
-Two more concerns are handled here:
+Three more concerns are handled here:
- **Lazy per-item setup**: a single outer `IntersectionObserver` rooted at the viewport drives setup and the start/stop of the inner swipe observers. Items only get wired up the first time they scroll into view, and items that scroll off-screen have their swipe observer paused. This keeps the active observer count bounded and avoids reading layout-dependent values (like `clientWidth`) before the item has been rendered.
- **Dynamic items**: real lists grow over time (initial render, infinite scroll, server push). A `MutationObserver` on the `<ul>` registers any newly added items with the outer observer.
+- **Action buttons**: a click (or the Enter key) on an item's action button runs the same `commit` function as the swipe it stands in for, so both paths share the focus move, the announcement and the removal animation. The action color and icon are revealed by scrolling the track during a swipe, so they don't appear when a button is used.
```js
// Per-item handles. Populated when an item is first lazily wired up; read by
@@ -274,9 +311,7 @@ function setupItem(item) {
// The IO entry's boundingClientRect is the last reliable measurement
// before the animation starts; reuse it for both the pre-collapse
// height and the slide-off translate distance.
- removeItem(item, content, direction, entry);
- viewportObserver.unobserve(item);
- observer.disconnect();
+ commit(direction, entry);
return;
}
@@ -294,15 +329,58 @@ function setupItem(item) {
threshold: [commitThreshold, activateThreshold],
});
+ // The swipe and the action buttons all commit through here, so they share
+ // one removal path. The guard stops a second swipe or click from removing
+ // the row twice.
+ function commit(direction, entry) {
+ if (item.classList.contains('is-removing')) return;
+ removeItem(item, content, direction, entry);
+ viewportObserver.unobserve(item);
+ observer.disconnect();
+ }
+
// Return the handle without starting observation; the outer viewport observer
// calls `observer.observe(content)` once the item is in view.
- const handle = {observer, content};
+ const handle = {observer, content, track, commit};
swipeObservers.set(item, handle);
return handle;
}
async function removeItem(item, content, direction, entry) {
- const opts = { duration: 300, easing: 'ease', fill: 'forwards' };
+ // Removing or inerting the row drops focus to <body> if focus is inside it,
+ // so move focus to the next row first (or the previous row, or the list
+ // heading when the list is now empty). Rows still collapsing are skipped.
+ // Keep focus on the same kind of element: if the row itself had focus
+ // (some browsers make the track a Tab stop even when it contains buttons),
+ // focus the next row, so the larger row focus indicator appears where the
+ // user expects it; otherwise focus the next row's first button.
+ const list = item.parentElement;
+ if (item.contains(document.activeElement)) {
+ const rows = [...list.children].filter(
+ (row) => row === item || !row.classList.contains('is-removing'),
+ );
+ const index = rows.indexOf(item);
+ const next = rows[index + 1] ?? rows[index - 1];
+ const listHeading = document.getElementById(list.getAttribute('aria-labelledby'));
+ const firstButton = next?.querySelector('button');
+ const target = document.activeElement.matches('.SwipeableList-track')
+ ? next?.querySelector('.SwipeableList-track')
+ : firstButton;
+ (target ?? listHeading).focus();
+ // Not every browser lets the track take focus; fall back to the button.
+ if (target && document.activeElement !== target) (firstButton ?? listHeading).focus();
+ }
+
+ // A row disappearing isn't announced, so say which item was removed in
+ // the page's role="status" element from Step 1.
+ const label = item.querySelector('.SwipeableList-label').textContent;
+ document.querySelector('.SwipeableList-status').textContent = `${label} removed`;
+
+ // Sliding the row off-screen is large movement, so skip it for users who
+ // prefer reduced motion and keep a shorter collapse instead.
+ // (150ms and 300ms are example durations.)
+ const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const opts = { duration: reduce ? 150 : 300, easing: 'ease', fill: 'forwards' };
const rect = entry.boundingClientRect;
// Content's pixel offset from the track's left edge.
@@ -320,7 +398,7 @@ async function removeItem(item, content, direction, entry) {
// smooth scroll-snap has scrolled the content fully off-screen.
item.classList.add('is-removing');
item.animate([{ height: `${rect.height}px` }, { height: '0px' }], opts);
- content.animate([{ translate: `${translate}px` }], opts);
+ if (!reduce) content.animate([{ translate: `${translate}px` }], opts);
await Promise.allSettled(
item.getAnimations({ subtree: true }).map((a) => a.finished),
);
@@ -351,8 +429,8 @@ function setupList(list) {
// Pick up items added later (initial render after data loads, infinite
// scroll, server push). Removals don't need MutationObserver handling —
- // the commit branch above already unobserves the item before removing it
- // from the DOM.
+ // `commit()` above already unobserves the item before removing it from the
+ // DOM.
new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
@@ -363,6 +441,22 @@ function setupList(list) {
}
}
}).observe(list, { childList: true });
+
+ // Delegate from the list so items added later work too. A keyboard user can
+ // reach a button before its row has scrolled into view, so set the item up
+ // on demand.
+ list.addEventListener('click', (event) => {
+ const button = event.target.closest('.SwipeableList-action');
+ const item = button?.closest('.SwipeableList-item');
+ if (!item) return;
+ const handle = swipeObservers.get(item) ?? setupItem(item);
+ // Commit in the direction of the swipe this button stands in for, passing
+ // the same measurements an IntersectionObserver entry carries.
+ handle.commit(button.dataset.direction, {
+ boundingClientRect: handle.content.getBoundingClientRect(),
+ rootBounds: handle.track.getBoundingClientRect(),
+ });
+ });
}
document.querySelectorAll('.SwipeableList').forEach(setupList);
@@ -382,15 +476,15 @@ The scroll/snap/observation mechanics are unchanged.
A single row can also expose **two different actions**: one for a left swipe and one for a right swipe (e.g., "archive" on right, "delete" on left), the way many native mail apps do it. The scroll, snap, and commit-detection mechanics don't change at all — the only thing that changes is what happens at commit time.
-In Step 4, the commit branch always calls `removeItem(...)`. To support two actions, pick the handler based on `direction`:
+In Step 4, the `commit` function always calls `removeItem(...)`. To support two actions, pick the handler based on `direction`, and give each action its own button whose `data-direction` is the direction of the swipe it stands in for (Step 1):
```js
-if (ratio < commitThreshold) {
+function commit(direction, entry) {
+ if (item.classList.contains('is-removing')) return;
const handler = direction === 'left' ? archiveItem : removeItem;
handler(item, content, direction, entry);
viewportObserver.unobserve(item);
observer.disconnect();
- return;
}
```
@@ -439,10 +533,14 @@ With this setup, the spacers no longer need their own background-color (the trac
- **DO** commit at a threshold *before* the snap settles (e.g., `commitThreshold ≈ 0.2`) rather than waiting for the content to be fully off-screen. This lets the remove animation start during the gesture, which feels significantly more responsive than waiting for the snap to land.
- **DO** drive per-item setup from an outer viewport `IntersectionObserver` rather than wiring every item up at page load. This avoids reading layout-dependent values (`clientWidth`, etc.) before items have been rendered, and keeps the active observer count proportional to what the user can actually see.
- **DO** use a `MutationObserver` on the list when items are added dynamically (initial render after data loads, infinite scroll, server push). Without it, items appended after page load won't get wired up.
-- **DO NOT** rely on `pointerdown`/`pointermove`/`pointerup` to drive a manual transform. You'll lose momentum, snap-back, keyboard accessibility, and reduced-motion handling that the browser gives you for free.
-- **DO** confirm destructive actions when appropriate. For "remove", consider showing an undo toast after the swipe completes; the gesture is fast and easy to trigger by accident.
-- **DO** ensure the scroll track is focusable, keyboard accessible, and that there is a visual focus affordance.
-- **DO** provide accessible alternatives for any relevant actions triggered by the swipe (e.g., a visible button, context menu, or edit mode).
+- **DO NOT** rely on `pointerdown`/`pointermove`/`pointerup` to drive a manual transform. You'll lose the momentum, snap-back, and keyboard scrolling that native scrolling gives you for free.
+- **DO** confirm destructive actions when appropriate. For "remove", consider showing an undo toast after the swipe completes; the gesture is fast and easy to trigger by accident. Also announce the result (for example, "Item One removed") by writing it into a `role="status"` element that is already in the page, because screen readers only announce changes to live regions that existed before the change.
+
+## Accessibility considerations
+
+To adhere to WCAG 2.5.1 Pointer Gestures, functionality must not be available solely through swiping gestures. Visible button elements are an accessible alternative way to activate the same functionality. Buttons provide people with disabilities, particularly people using voice control software, with a usable way of activating the same functionality. Make each button at least 24×24 CSS pixels (WCAG 2.5.8 Target Size (Minimum)), name it after the item it acts on, and ensure that there's a way of moving focus to the button and operating it using a keyboard alone. Once a row contains a button, don't add `tabindex` to the track: arrow keys on a focused track commit the action with no confirmation.
+
+Another way of adhering to the 2.5.1 Pointer Gestures success criterion is by ensuring that the functionality exists elsewhere. For example, in an email app's inbox, if the email can be swiped left to be favorited, but this can also be achieved via a "Favorite email" button after navigating to an email, this would be sufficient, as long as that button can also be reached and operated with a keyboard. If the intended use case may require many repeated actions, this approach will be less usable, as it would require people with disabilities to have to spend more time accessing the alternative control. A menu opened with a long press that offers the same actions can also be a sufficient alternative, but it's often not as discoverable as permanently visible buttons. If the buttons only appear on hover or focus, also show them when the item is tapped, so touch users can reach them.
## Fallback strategies
@@ -532,14 +630,14 @@ function setupItem(item) {
}
```
-Unobserve the track before the row's height animation runs in `removeItem`, otherwise the height change re-triggers the resize callback during removal. Add this alongside the existing `viewportObserver.unobserve(item)` in the commit branch:
+Unobserve the track before the row's height animation runs in `removeItem`, otherwise the height change re-triggers the resize callback during removal. Add this alongside the existing `viewportObserver.unobserve(item)` in the `commit` function (Step 4):
```js
-if (ratio < commitThreshold) {
+function commit(direction, entry) {
+ if (item.classList.contains('is-removing')) return;
removeItem(item, content, direction, entry);
viewportObserver.unobserve(item);
if (needsScrollWorkaround) trackResizeObserver.unobserve(track);
observer.disconnect();
- return;
}
```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-reveal.md b/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-reveal.md
index 13a7204..b6b9975 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-reveal.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-reveal.md
@@ -10,7 +10,7 @@ Whether you are revealing action buttons on a list item or a side menu next to a
### Step 1: Mark up the swipe wrapper, content, and revealed panel
-Place the foreground content first and the revealed controls (action buttons or a side menu) second inside the `.SwipeReveal` scroll container. Because the content is first in DOM order, the scroll container naturally starts at scroll offset `0` with the panel hidden off-screen to the right.
+Place the foreground content first and the revealed controls (action buttons or a side menu) second inside the `.SwipeReveal` scroll container. Because the content is first in DOM order, the scroll container naturally starts at scroll offset `0` with the panel hidden off-screen to the right. For each swipe action, ensure that the accessible name includes the content that it relates to, so that people can differentiate between the available controls.
```html
<!-- Example A: List item with revealable action buttons -->
@@ -18,11 +18,12 @@ Place the foreground content first and the revealed controls (action buttons or
<div class="SwipeReveal-content">
<strong>Design review notes</strong>
<p>Updated component specs for the Q3 release.</p>
+ <button aria-label="Design review notes actions" aria-expanded="false">…</button>
</div>
<div class="SwipeReveal-panel" role="group" aria-label="Item actions">
- <button type="button">Pin</button>
- <button type="button">Archive</button>
- <button type="button">Delete</button>
+ <button type="button" tabindex="-1">Pin</button>
+ <button type="button" tabindex="-1">Archive</button>
+ <button type="button" tabindex="-1">Delete</button>
</div>
</div>
@@ -31,11 +32,12 @@ Place the foreground content first and the revealed controls (action buttons or
<div class="SwipeReveal-content is-scrollable" tabindex="0">
<h2>Article Preview</h2>
<p>Scroll vertically through this pane, or swipe left to reveal the side menu...</p>
+ <button aria-label="Article actions" aria-expanded="false">…</button>
</div>
<nav class="SwipeReveal-panel" aria-label="Contextual menu">
- <a href="#share">Share</a>
- <a href="#bookmark">Bookmark</a>
- <a href="#export">Export PDF</a>
+ <a href="#share" tabindex="-1">Share</a>
+ <a href="#bookmark" tabindex="-1">Bookmark</a>
+ <a href="#export" tabindex="-1">Export PDF</a>
</nav>
</div>
```
@@ -107,25 +109,77 @@ Make `.SwipeReveal` a two-column grid (`grid-template-columns: 100% max-content`
> If you also want to reveal controls on the left (`inline-start`) side using three columns (`grid-template-columns: max-content 100% max-content`) or two columns (`max-content 100%`), place the leading `.SwipeReveal-panel` before `.SwipeReveal-content`. Because `.SwipeReveal-content` has `scroll-initial-target: nearest`, the scroll container initially rests on the content column rather than the leading panel.
-### Step 3: Snap focusable content panes back into view on keyboard focus
+### Step 3: Reveal controls when trigger button is activated
-Because the buttons or links inside `.SwipeReveal-panel` are off-screen at rest, tabbing into them with a keyboard automatically scrolls `.SwipeReveal` to reveal the focused control. However, because `.SwipeReveal-content` spans `100%` of the outer container's width, most of it remains inside the scrollport even while the side panel is open—so pressing `Shift+Tab` to move focus back onto `.SwipeReveal-content` (or onto a focusable element inside it) will not automatically scroll the track back to `0`.
-
-Listen for `focusin` on `.SwipeReveal-content` and check `event.target.matches(':focus-visible')` so keyboard focus on the pane or any descendant snaps `.SwipeReveal-content` back to the start without interfering with pointer clicks or touch drags:
+Because the buttons or links inside `.SwipeReveal-panel` are off-screen at rest and do not receive focus by default (due to the `tabindex="-1"` attributes), when the corresponding trigger button is activated, we need to ensure that they are revealed as expected. When this happens, we also need to set the `tabindex` attributes to be `tabindex="0"` so that people can move to them and interact with them, and set the `aria-expanded` attribute on the trigger control to be `aria-expanded="true"`. When the trigger control is interacted with when the controls are already revealed, these changes should be reversed.
```js
-for (const content of document.querySelectorAll('.SwipeReveal-content')) {
- content.addEventListener('focusin', (event) => {
- if (event.target.matches(':focus-visible')) {
- content.scrollIntoView({
- block: 'nearest',
- inline: 'start',
- });
+for (const trigger of document.querySelectorAll('.SwipeReveal-content [aria-label$="actions"]')) {
+ trigger.addEventListener('click', () => {
+ const reveal = trigger.closest('.SwipeReveal');
+ if (!reveal) return;
+
+ const label = (trigger.getAttribute('aria-label') || '').toLowerCase();
+ const isExpanded = trigger.getAttribute('aria-expanded') === 'true';
+ if (isExpanded) {
+ if (label.includes('leading')) {
+ let leadingScrollPanelWidth = reveal.querySelector('.SwipeReveal-panel').offsetWidth;
+ reveal.scrollTo({
+ left: leadingScrollPanelWidth,
+ behavior: 'smooth',
+ });
+ } else if (label.includes('trailing')) {
+ let leadingScrollPanelWidth = reveal.querySelector('.SwipeReveal-panel').offsetWidth;
+ reveal.scrollTo({
+ left: leadingScrollPanelWidth,
+ behavior: 'smooth',
+ });
+ } else {
+ reveal.scrollTo({
+ left: 0,
+ behavior: 'smooth',
+ });
+ }
+
+ for (const actionButton of reveal.querySelectorAll('[aria-label$="actions"]')) {
+ actionButton.setAttribute('aria-expanded', 'false');
+ }
+ setActionTabIndexes(reveal, false);
+ return;
+ }
+
+ const panels = Array.from(reveal.querySelectorAll('.SwipeReveal-panel'));
+ if (panels.length === 0) return;
+
+ let targetScrollLeft = reveal.scrollWidth;
+
+ if (label.includes('leading')) {
+ targetScrollLeft = 0;
+ } else if (label.includes('trailing')) {
+ targetScrollLeft = reveal.scrollWidth;
+ } else if (panels.length === 1) {
+ targetScrollLeft = reveal.scrollWidth;
+ } else {
+ const content = reveal.querySelector('.SwipeReveal-content');
+ const firstTrigger = content.querySelector('[aria-label$="actions"]');
+ targetScrollLeft = trigger === firstTrigger ? 0 : reveal.scrollWidth;
+ }
+
+ reveal.scrollTo({
+ left: targetScrollLeft,
+ behavior: 'smooth',
+ });
+
+ for (const actionButton of reveal.querySelectorAll('[aria-label$="actions"]')) {
+ actionButton.setAttribute('aria-expanded', actionButton === trigger ? 'true' : 'false');
}
+ setActionTabIndexes(reveal, true);
});
}
```
+Along with this, use `scroll-snap-realtime-feedback` (via `npx -y modern-web-guidance@latest retrieve "scroll-snap-realtime-feedback"`) to ensure that the accessibility state information is kept up to date, if someone swipes open the associated content, rather than triggering it directly with the button.
+
## Best practices and pitfalls
- **DO** use `scroll-snap-type: x mandatory` rather than `proximity`. With `proximity`, a light swipe can leave the action buttons or side menu partially exposed at rest.
@@ -134,6 +188,12 @@ for (const content of document.querySelectorAll('.SwipeReveal-content')) {
- **DO** implement revealed actions and side-menu items as real focusable DOM controls (`<button>`, `<a>`). When `.SwipeReveal-content` is focusable or contains focusable controls, pair a `focusin` listener with `event.target.matches(':focus-visible')` to call `scrollIntoView({ block: 'nearest', inline: 'start' })` so tabbing back into the content pane closes the side panel without affecting pointer interactions.
- **DO NOT** intercept `wheel`, `touchmove`, or `pointermove` events in JavaScript to manually translate the content or emulate scroll chaining. Main-thread gesture interception blocks compositor-driven scrolling, breaks native scroll momentum, and degrades responsiveness.
+## Accessibility considerations
+
+To adhere to WCAG 2.5.1 Pointer Gestures, functionality must not be available solely through swiping gestures. Visible button elements are an accessible alternative way to activate the same functionality. Buttons provide people with disabilities, particularly people using voice control software, with a usable way of activating the same functionality. Make each button at least 24×24 CSS pixels (WCAG 2.5.8 Target Size (Minimum)) and ensure that there's a way of moving focus to the button and operating it using a keyboard alone.
+
+Another way of adhering to the 2.5.1 Pointer Gestures success criterion is by ensuring that the functionality exists elsewhere. For example, in an email app's inbox, if the email can be swiped left to be favourited, but this can also be achieved via a "Favourite email" button after navigating to an email, this would be sufficient. If the intended use case may require many repeated actions, this approach will be less usable, as it would require people with disabilities to have to spend more time accessing the alternative control. Operating system or browser features (such as a long press on iOS) can also be a sufficient alternative, but are often not as discoverable as permanently visible buttons.
+
## Fallback
Browser support for scroll-initial-target: Limited availability.
diff --git a/skills/modern-web-guidance/guides/ui-components/accordion.md b/skills/modern-web-guidance/guides/ui-components/accordion.md
new file mode 100644
index 0000000..bb969b7
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/accordion.md
@@ -0,0 +1,343 @@
+# Accordion
+
+Build accordions from a set of adjacent `details` elements.
+
+If the accordion is a distinct section of the page, group its items in an element with an accessible name, such as a `section` labeled by the group heading.
+
+```html
+<section class="accordion" aria-labelledby="faq-heading">
+ <h2 id="faq-heading">Frequently Asked Questions</h2>
+ <details>
+ <summary>Lorem ipsum dolor sit amet?</summary>
+ <!-- answer 1 -->
+ </details>
+ <details>
+ <summary>Consectetur adipiscing elit?</summary>
+ <!-- answer 2 -->
+ </details>
+</section>
+```
+
+**Warning:** Do not put headings inside `summary`. JAWS and TalkBack expose `summary` as a button and drop any heading inside it, so their users cannot move between items by heading.
+If each item needs its own heading, build a custom accordion instead (see below).
+
+Accessibility notes:
+- Do not wrap every small accordion in a landmark or `region`; that adds navigation noise for screen reader users.
+- Do not add arrow key navigation, roving `tabindex`, or `Home`/`End` handling.
+Accordion contents are often long enough to need scrolling, and arrow keys on a focused trigger are how keyboard users scroll.
+- If a heading for the entire accordion is not desirable, use an `aria-label` on the container element to provide an accessible name for the group.
+
+## Exclusive accordions
+
+An exclusive accordion only allows one item to be open at a time.
+
+To make an accordion exclusive, add the same `name` to each `details` element that should be part of the exclusive group.
+Ensure that `name` is not used elsewhere on the page unless it is intended to be part of the same exclusive accordion group.
+
+```html
+<section class="accordion" aria-labelledby="faq-heading">
+ <h2 id="faq-heading">Frequently Asked Questions</h2>
+ <details name="faq-question">
+ <summary>Lorem ipsum dolor sit amet?</summary>
+ <!-- answer 1 -->
+ </details>
+ <details name="faq-question">
+ <summary>Consectetur adipiscing elit?</summary>
+ <!-- answer 2 -->
+ </details>
+</section>
+```
+
+Avoid exclusive accordions, as they can produce suboptimal user experience:
+- Sometimes users want to reference between the contents of multiple items, which exclusive accordions prevent.
+- They also can cause content to shift out of the user’s view which can cause significant problems for those using screen magnifiers.
+
+### Keeping one item always open
+
+To require that one item is always open, stop the open item’s `summary` from closing it and expose it as disabled. Opening another item still closes it through `name`. This compounds the downsides above, since users can never reclaim the space, so only use it when the layout depends on an item being open.
+
+```html
+<section class="accordion always-open" aria-labelledby="plans-heading">
+ <h2 id="plans-heading">Plans</h2>
+ <details name="plan" open>
+ <!-- Mirrors the open state; the script keeps it in sync -->
+ <summary aria-disabled="true">Basic</summary>
+ <!-- Basic plan -->
+ </details>
+ <details name="plan">
+ <summary>Pro</summary>
+ <!-- Pro plan -->
+ </details>
+</section>
+```
+
+```javascript
+// Enter and Space on a summary also dispatch click, so this covers keyboard too
+document.addEventListener("click", event => {
+ if (event.target.closest(".accordion.always-open details[open] > summary")) event.preventDefault();
+});
+
+// toggle does not bubble, hence capture
+document.addEventListener("toggle", event => {
+ if (!event.target.matches(".accordion.always-open details")) return;
+ event.target.querySelector(":scope > summary").setAttribute("aria-disabled", event.target.open);
+}, { capture: true });
+```
+
+Keep the disabled `summary` focusable so focus is not lost when the item a user just opened becomes disabled, but exclude it from hover and pointer styles so it does not look clickable:
+
+```css
+/* :where() keeps the guard from raising specificity */
+summary:where(:not([aria-disabled="true"])) {
+ cursor: pointer;
+
+ &:hover {
+ background: var(--color-hover);
+ }
+}
+```
+
+## Optional: Expand/Collapse All button
+
+For non-exclusive accordions, a single button that expands or collapses every item can improve user experience.
+Give it `aria-expanded` and keep it in sync with the items, so screen readers announce the change (VoiceOver does not reliably announce a label change on its own).
+Mark it expanded only once every item is open; in a mixed state it reads "Expand all" and pressing it opens everything.
+
+```html
+<section class="accordion" id="support-accordion" aria-labelledby="support">
+ <h2 id="support">Support</h2>
+ <button type="button" commandfor="support-accordion" command="--toggle-all" aria-expanded="false">
+ <span class="expand">Expand all</span>
+ <span class="collapse">Collapse all</span>
+ </button>
+ <!-- Accordion items -->
+</section>
+```
+
+```css
+/* Show the label for the action the button will perform */
+[command="--toggle-all"][aria-expanded="true"] .expand,
+[command="--toggle-all"][aria-expanded="false"] .collapse {
+ display: none;
+}
+```
+
+```javascript
+document.addEventListener("command", event => {
+ if (event.command !== "--toggle-all") return;
+ const expand = event.source.getAttribute("aria-expanded") !== "true";
+
+ // Command events fire on the commandfor target
+ for (const details of event.target.querySelectorAll(":scope > details")) {
+ details.open = expand;
+ }
+}, { capture: true }); // Command events do not bubble, hence capture
+
+// Items also open and close individually, so derive the button state from them
+document.addEventListener("toggle", event => {
+ if (!event.target.matches(".accordion > details")) return;
+ const accordion = event.target.parentElement;
+ const button = accordion.querySelector(':scope > [command="--toggle-all"]');
+ if (!button) return;
+
+ const items = accordion.querySelectorAll(":scope > details");
+ button.setAttribute("aria-expanded", Array.prototype.every.call(items, details => details.open));
+}, { capture: true }); // toggle does not bubble, hence capture
+```
+
+Separate buttons are also possible and improve discoverability, at the cost of _feedback_: there are states where one of the buttons will produce no visible result, and disabling it accessibly introduces challenges and increases complexity.
+
+## Styling
+
+The disclosed content lives in the `::details-content` pseudo-element. While closed it is hidden with `content-visibility: hidden`, not `display: none`, which is what keeps it findable and lets its size animate. Style the item on `details`, the trigger on `summary`, and the content on `details::details-content`.
+
+### Customizing the marker
+
+`summary` renders as a list item, so its disclosure triangle is a `::marker`. Remove it with `list-style: none` and draw your own with `::before`, which unlike `::marker` can be sized, positioned, and animated.
+Render the icon as a mask so it follows the text color, and rotate it for the closed state so one icon serves both states and both writing directions.
+See `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`) for more details on including and customizing icons via CSS.
+
+Prefer keeping the marker directly next to the label text, not pushed to the opposite edge of the summary, especially for accordions that can get wide.
+A marker far from its label makes it harder for users to associate with the correct label, and falls outside the field of view of users with low vision or screen magnification.
+Right before the label text is preferable to right after, as it facilitates vertical scanning.
+
+```css
+summary {
+ /* Removes the default triangle */
+ list-style: none;
+ display: flex;
+ align-items: center;
+ gap: 0.5ch;
+
+ &::before {
+ content: "";
+ inline-size: 1em;
+ block-size: 1em;
+ flex-shrink: 0;
+ background-color: currentColor;
+ /* Example chevron pointing down, the open state; any single-color SVG works */
+ mask: url("icons/chevron-down.svg") no-repeat center / contain;
+ /* Closed: point toward the inline end */
+ rotate: -90deg;
+ }
+
+ &:dir(rtl)::before {
+ rotate: 90deg;
+ }
+
+ /* Rotate rather than swap icons, so the change can animate */
+ details[open] > &::before {
+ rotate: 0deg;
+ }
+
+ @media (prefers-reduced-motion: no-preference) {
+ &::before {
+ transition: rotate 0.2s;
+ }
+ }
+}
+```
+
+### Slide up/down animation
+
+To animate opening and closing, transition `block-size` between `0` and its intrinsic size, and transition `content-visibility` discretely so the content stays rendered until the collapse finishes.
+
+```css
+details::details-content {
+ /* Lets block-size transition to and from its intrinsic auto size */
+ interpolate-size: allow-keywords;
+ overflow: clip;
+ /* Keeps layout containment constant across states; otherwise content-visibility toggling it
+ makes the transition jitter when the content has outward margins (e.g. a nested p) */
+ contain: layout;
+}
+
+details:not([open])::details-content {
+ block-size: 0;
+}
+
+/* Only animate for users who have not asked for reduced motion */
+@media (prefers-reduced-motion: no-preference) {
+ details::details-content {
+ transition: block-size, content-visibility, display;
+ /* Example duration; match the surrounding motion design */
+ transition-duration: 0.3s;
+ transition-timing-function: ease-in-out;
+ /* Defers content-visibility: hidden until the collapse ends */
+ transition-behavior: allow-discrete;
+ }
+}
+```
+
+See `animate-to-intrinsic-sizes` (via `npx -y modern-web-guidance@latest retrieve "animate-to-intrinsic-sizes"`) for more details.
+
+## Excluding a `details` element’s contents from find-in-page
+
+If it’s undesirable for a `details` element’s contents to be included in what’s matched with the browser’s find-in-page feature, hide the closed contents with `display: none`. To keep the slide animation, set the collapsed size in `@starting-style`. See `animate-element-entry-exit` (via `npx -y modern-web-guidance@latest retrieve "animate-element-entry-exit"`) for more details.
+
+```css
+.accordion.unsearchable > details {
+ /* Excludes the contents from find-in-page */
+ &:not([open])::details-content {
+ display: none;
+ }
+
+ /* Where the opening transition starts from, since display: none has no size */
+ &[open]::details-content {
+ @starting-style {
+ block-size: 0;
+ }
+ }
+}
+```
+
+## Custom accordion
+
+Use a custom accordion only when each item is a section of the page that needs its own heading, such as a FAQ or a long reference page where screen reader users move between items by heading.
+It costs JavaScript for every behavior, including exclusivity, so prefer `details` everywhere else.
+
+Place the `button` inside the heading so the heading keeps its semantics, and put the content element immediately after the heading.
+Hide the content with `hidden="until-found"` so it stays findable, or with plain `hidden` to exclude it from find-in-page.
+`aria-controls` on the trigger is optional; screen readers gain nothing from it.
+
+```html
+<section class="accordion" aria-labelledby="faq-heading">
+ <h2 id="faq-heading">Frequently Asked Questions</h2>
+ <h3>
+ <button type="button" commandfor="answer-1" command="--toggle" aria-expanded="false">How do I reset my password?</button>
+ </h3>
+ <div id="answer-1" hidden="until-found"><!-- Answer --></div>
+</section>
+```
+
+```javascript
+document.addEventListener("command", event => {
+ if (event.command !== "--toggle") return;
+ const content = event.target;
+
+ content.hidden = content.hidden ? false : "until-found";
+ event.source.setAttribute("aria-expanded", !content.hidden);
+}, { capture: true }); // Command events do not bubble, hence capture
+
+// Find-in-page reveals the content directly, so mirror that into the trigger
+document.addEventListener("beforematch", event => {
+ document.querySelector(`[commandfor="${CSS.escape(event.target.id)}"]`)?.setAttribute("aria-expanded", "true");
+});
+```
+
+To make it exclusive, hide the other items' content and reset their triggers in both handlers, since find-in-page can also open an item.
+See `custom-button-actions` (via `npx -y modern-web-guidance@latest retrieve "custom-button-actions"`) for more details on custom commands and `search-hidden-content` (via `npx -y modern-web-guidance@latest retrieve "search-hidden-content"`) for `hidden="until-found"`.
+
+## Fallback strategies
+
+### Mutually exclusive `details`
+
+Baseline status for Mutually exclusive <details> elements: Newly available. It's been Baseline since 2024-09-03.
+Supported by: Chrome 120 (Dec 2023), Edge 120 (Dec 2023), Firefox 130 (Sep 2024), and Safari 17.2 (Dec 2023).
+
+In browsers that don't support `name` on `details`, several items stay open, which is still a working (non-exclusive) accordion.
+If the exclusivity is crucial to the user experience, you can implement a fallback. It also keeps always-open accordions working, since the open item still closes when another opens:
+
+```javascript
+// Only needed where the name attribute is unsupported
+if (!Object.hasOwn(HTMLDetailsElement.prototype, "name")) {
+ document.addEventListener("toggle", event => {
+ const details = event.target;
+ if (!(details instanceof HTMLDetailsElement) || !details.open || !details.hasAttribute("name")) return;
+
+ const name = CSS.escape(details.getAttribute("name"));
+ for (const other of document.querySelectorAll(`details[name="${name}"]`)) {
+ if (other !== details) other.open = false;
+ }
+ }, { capture: true }); // toggle does not bubble, hence capture
+}
+```
+
+### Expand all and Collapse all
+
+Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
+Supported by: Chrome 135 (Apr 2025), Edge 135 (Apr 2025), Firefox 144 (Oct 2025), and Safari 26.2 (Dec 2025).
+
+If your Baseline target does not support invoker commands, the button does nothing. Feature-detect with `Object.hasOwn(HTMLButtonElement.prototype, "commandForElement")` and fall back to a `click` listener that runs the same loop. See `custom-button-actions` (via `npx -y modern-web-guidance@latest retrieve "custom-button-actions"`) for more details.
+
+### Open and close animation
+
+Baseline status for ::details-content: Newly available. It's been Baseline since 2025-09-16.
+Supported by: Chrome 131 (Nov 2024), Edge 131 (Nov 2024), Firefox 143 (Sep 2025), and Safari 18.4 (Mar 2025).
+
+Browser support for interpolate-size: Limited availability.
+Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
+Unsupported in: Firefox and Safari.
+
+Baseline status for transition-behavior: Newly available. It's been Baseline since 2024-08-06.
+Supported by: Chrome 117 (Sep 2023), Edge 117 (Sep 2023), Firefox 129 (Aug 2024), and Safari 17.4 (Mar 2024).
+
+The animation is a progressive enhancement and needs no fallback. Without `interpolate-size`, items open and close instantly. Without `transition-behavior`, the content hides at the start of the collapse and the height animates empty, while opening still animates.
+
+### Custom accordion
+
+Browser support for hidden="until-found": Limited availability.
+Supported by: Chrome 102 (May 2022), Edge 102 (May 2022), and Firefox 148 (Feb 2026).
+Unsupported in: Safari.
+
+Where `until-found` is unsupported, the attribute behaves as plain `hidden`: the content is hidden but not findable, and the accordion still works.
diff --git a/skills/modern-web-guidance/guides/ui-components/app-menus.md b/skills/modern-web-guidance/guides/ui-components/app-menus.md
new file mode 100644
index 0000000..9ebbb85
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/app-menus.md
@@ -0,0 +1,216 @@
+# Build an application menu bar
+
+An application menu bar (File, Edit, View, Help) is a row of menus that behaves as one widget: one `Tab` stop, `ArrowLeft` and `ArrowRight` move between menus, focusing a menu title shows its menu, and once one menu is open, pointing at another title switches to it. Use it for an application command bar.
+
+Do not use it for site navigation (a short list of links users `Tab` through) or for a few unrelated menu buttons in a toolbar or page header. Those are standalone menus: each trigger is its own `Tab` stop, looks like a separate button, and has none of the bar behavior below.
+
+Each menu in the bar is a complete popup menu: invoker-triggered popover, nested focusgroup, submenus, separators, checkable items, positioning, pointer handling, and fallbacks. Build them as described in `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`); this guide covers only what the bar adds on top of each menu.
+
+## Structure
+
+* Put `role="menubar"` with an `aria-label` on the container of the top-level triggers, never on a popover. Each top-level trigger is a direct child of the menubar, immediately followed by its popover.
+* Style the bar as one continuous strip with no gaps or borders between triggers. Visually separate buttons signal one `Tab` stop each; a continuous bar signals one widget.
+* Give the trigger with `aria-expanded="true"` a visible active style so users can tell which menu is open or previewed.
+
+```html
+<div role="menubar" aria-label="Document commands">
+ <!-- Only the active trigger is tabbable; the script moves tabindex with ArrowLeft and ArrowRight. -->
+ <button id="file-trigger" type="button" aria-haspopup="menu" aria-expanded="false"
+ commandfor="file-menu" command="toggle-popover">File</button>
+ <div id="file-menu" popover="auto">
+ <div focusgroup="menu nomemory" aria-labelledby="file-trigger">
+ <!-- Items and submenus as in the menu guide -->
+ </div>
+ </div>
+
+ <button id="edit-trigger" type="button" aria-haspopup="menu" aria-expanded="false"
+ commandfor="edit-menu" command="toggle-popover" tabindex="-1">Edit</button>
+ <div id="edit-menu" popover="auto">
+ <div focusgroup="menu nomemory" aria-labelledby="edit-trigger">
+ <!-- … -->
+ </div>
+ </div>
+</div>
+```
+
+## Keyboard and focus
+
+The menu guide's keyboard model applies inside every menu. The bar adds, on top of it:
+
+* **One tab stop.** `Tab` enters at the first top-level trigger. `ArrowLeft` and `ArrowRight` move between top-level triggers and wrap at either end. `Home` and `End` on a trigger enter its menu at the first or last item.
+ * **Note: which trigger `Tab` returns to.** The APG allows either the first trigger or the last one used. The guide specifies the first, but moving the tab stop with `ArrowLeft` and `ArrowRight` means that after keyboard navigation `Shift`+`Tab` returns to the last trigger reached. Pointer use does not move it, so the same sequence can land on a different trigger. Either behavior is acceptable; pick one and keep it consistent.
+* **Preview.** Focusing a top-level trigger shows its menu and sets `aria-expanded="true"`. Focus stays on the trigger, and no item is focused. Blurring the trigger closes a preview-only menu.
+* **Enter and Space on a preview.** They close the preview and keep focus on the trigger. The native `toggle-popover` action handles this, so the script must not intercept these keys.
+* **ArrowDown on a preview.** Converts it to an open menu and focuses the first item.
+* **ArrowLeft or ArrowRight in an open top-level menu.** Closes it and previews the adjacent menu with focus on its trigger, wrapping at either end. `ArrowDown` then enters it. Left and Right never land inside a menu.
+* **ArrowRight on a submenu item without a child submenu.** Closes the hierarchy and previews the next top-level menu while focus stays on its trigger. `ArrowDown` then enters it.
+* **Pointer over another top-level trigger while a menu is open.** Closes it and previews the hovered one, focusing its trigger without a ring. Nothing open: hover does nothing.
+* **Tab.** Leaves the bar from a trigger or from inside any menu, closing every open menu.
+
+## Implementing the bar
+
+1. **Roving tabindex.** Set `tabindex="0"` on the first top-level trigger and `-1` on the rest. When `ArrowLeft` or `ArrowRight` moves to another trigger, move the `0` with it. Do not put the triggers in a focusgroup: the bar needs preview on focus and menu switching, which focusgroup does not provide.
+2. **Preview on focus.** A top-level trigger's `focus` handler calls `menu.showPopover({ source: trigger })` so the menu anchors to it. Ignore focus returning from inside the trigger's own menu, or from another window (flag on window `blur`, cleared a tick after window `focus`, or app-switching reopens the last menu). Hide a previewed menu on `blur` unless focus moved into it.
+3. **Moving between menus.** One function closes every open top-level menu, moves the tabindex, and focuses the target trigger; preview on focus does the rest. Call it from `ArrowLeft`/`ArrowRight` on a trigger, from the same keys inside an open top-level menu, and from `ArrowRight` on a submenu item with no child submenu.
+
+```js
+// Direct children only: submenu triggers live inside the bar's nested popovers.
+const rootTriggers = [...document.querySelectorAll('[role="menubar"] > [commandfor]')];
+
+// Left/Right always land on the adjacent trigger as a preview, never inside its menu, as in
+// native menubars. ArrowDown then enters.
+function moveToRootTrigger(from, direction) {
+ const next = rootTriggers[(rootTriggers.indexOf(from) + direction + rootTriggers.length) % rootTriggers.length];
+ rootTriggers.forEach(trigger => { trigger.tabIndex = trigger === next ? 0 : -1; });
+ rootTriggers.map(menuFor).filter(isOpen).forEach(menu => menu.hidePopover());
+ next.focus({ preventScroll: true }); // Focusing the trigger previews its menu.
+}
+```
+
+4. **Hover switches open menus.** On `pointerenter` of a top-level trigger while another top-level menu is open: hide it, focus the hovered trigger without a ring (`focus({ focusVisible: false })`), and preview on focus previews it. Nothing open: do nothing. Keep `:hover` on top-level triggers: with nothing open it is plain button feedback, with a menu open the hover switches menus and focus follows.
+5. **Entering from a trigger.** `ArrowDown` on a previewed trigger focuses the first item; on a closed trigger it marks the menu to be entered and calls `trigger.click()`, so the invoker stays the only open path. `Home` and `End` preview the menu if needed, then focus its first or last enabled item.
+6. **Outside focus.** The `document` `focusin` listener that closes every menu must treat the menubar as inside the menu system, or `Tab` landing on a trigger closes the menu it just previewed.
+7. **Instant switching.** Native menubars switch between open menus without animation. If menus animate, disable the transition while another menu in the bar is already open:
+
+```css
+@media (prefers-reduced-motion: no-preference) {
+ /* Switching between open menubar menus is instant, as in native menubars. */
+ [role="menubar"]:has(> [popover]:popover-open) > [popover] {
+ transition: none;
+ }
+}
+```
+
+## Verify before finishing
+
+An instruction cannot guarantee behavior, so test the result. Open the page and check each of these with the real keyboard and mouse; fix and re-test any that fail. Check the menus themselves against the menu guide's list.
+
+* **One tab stop.** `Tab` lands on the first trigger once and previews its menu; `Shift`+`Tab` from the page content returns to the bar once, not to every trigger.
+* **Arrow keys.** `ArrowRight` and `ArrowLeft` on a trigger preview the adjacent menu, wrapping, without focusing an item; `ArrowDown` enters; inside an open menu, `ArrowRight` and `ArrowLeft` switch to the adjacent menu as a preview.
+* **Hover.** With File open, pointing at Edit switches to it instantly; with nothing open, pointing at a trigger does nothing.
+* **Window focus.** Switching to another window and back does not reopen the last menu.
+* **Leaving.** `Tab` from a trigger or from inside a menu closes everything and leaves the bar.
+
+## Fallback strategies
+
+The bar itself is roving tabindex, focus handling, and `showPopover()`, all widely supported script. Beyond the menus, the bar only adds the `[role="menubar"]:has(> [popover]:popover-open)` rule that disables the transition while switching; without `:has()`, switching animates like a plain open.
+
+The menus in the bar use focusgroup, popovers, invoker commands, anchor positioning, and `:has()`. Their fallbacks follow.
+
+### Fallbacks & browser support for focusgroup
+
+Browser support for focusgroup: Limited availability.
+Supported by: Chrome 150 (Jun 2026) and Edge 150 (Jul 2026).
+Unsupported in: Firefox and Safari.
+
+Keep `focusgroup="menu nomemory"` in the markup. If `'focusGroup' in HTMLElement.prototype` is false, install Up, Down, Home, and End, set `role="menu"` on each menu container, and `role="menuitem"` on buttons with no role; leave checkable items, `<hr>`, and `role="group"` alone. Never install it when native focusgroup is present. Submenu preview, open, and close are author script either way.
+
+```js
+if (!('focusGroup' in HTMLElement.prototype)) {
+ document.querySelectorAll('[focusgroup~="menu"]').forEach(group => {
+ group.setAttribute('role', 'menu');
+ group.querySelectorAll('button:not([role])').forEach(item => {
+ item.setAttribute('role', 'menuitem');
+ });
+ group.addEventListener('keydown', event => {
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
+ // Own items only: a nested submenu has its own focusgroup, a role="group" wrapper does not.
+ const items = [...group.querySelectorAll('button')]
+ .filter(item => item.closest('[focusgroup]') === group)
+ .filter(item => !item.disabled && item.getAttribute('aria-disabled') !== 'true');
+ const current = items.indexOf(document.activeElement);
+ if (current < 0) return;
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 :
+ (current + (event.key === 'ArrowUp' ? -1 : 1) + items.length) % items.length;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ items[next].focus({ preventScroll: true });
+ }, true);
+ });
+}
+```
+
+### Fallbacks & browser support for Popover
+
+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
+Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
+
+The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
+
+**Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
+ import("@oddbird/popover-polyfill");
+}
+```
+
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Fallbacks & browser support for Anchor positioning
+
+Browser support for Anchor positioning: Limited availability.
+Supported by: Safari 27 (Sep 2026).
+Unsupported in: Chrome, Edge, and Firefox.
+
+Without CSS Anchor Positioning, a popover falls back to the UA's centered viewport placement. Never ship that for a menu: it detaches the menu from its trigger, and a centered submenu covers its parent. Gate the anchored rules behind `@supports (position-area: block-end)` and position the menu from script when it fails:
+
+* Place the menu below its trigger (top level) or beside it (submenu), flipping to the other side and clamping to the viewport when it would overflow.
+* Run it in the `toggle` handler when the menu opens, and apply the result as `left` and `top` on the menu. Use `position: fixed` with `inset: auto` and `margin: 0` so the coordinates are viewport-relative.
+* Keep these overrides inside `@supports not (position-area: block-end)`, so browsers with anchor positioning are unaffected.
+
+Baseline status for the api.HTMLElement.showPopover.options_source_parameter.implicit_anchor_reference capability: Newly available. It's been Baseline since 2026-01-13.
+Supported by: Chrome 137 (May 2025), Edge 137 (May 2025), Firefox 147 (Jan 2026), and Safari 26 (Sep 2025).
+
+If targeting earlier implementations where `showPopover({ source })` does not establish an implicit anchor (no `source` on `ToggleEvent.prototype`), give each trigger a unique `anchor-name` and each menu a matching `position-anchor` from script, instead of writing per-menu CSS rules.
+
+For browsers without anchor positioning at all, see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`) for the polyfill route.
+
+### Fallbacks & browser support for Invoker commands
+
+Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
+Supported by: Chrome 135 (Apr 2025), Edge 135 (Apr 2025), Firefox 144 (Oct 2025), and Safari 26.2 (Dec 2025).
+
+Without invokers, `command="toggle-popover"` does nothing, so script must toggle the menu.
+
+* Feature-detect the interface, not an instance: `'commandForElement' in HTMLButtonElement.prototype`.
+* On each trigger `click`, call `preventDefault()` so a browser with invokers cannot toggle twice.
+* If the menu is open, close it with `closeAndRestore(menu)`. Otherwise call `menu.showPopover({ source: trigger })`.
+* Mark the menu in `enterOnOpen` unless the click came from the pressed trigger (`pointerTrigger`), so only keyboard opens enter the menu.
+* `Enter` and `Space` still work because they generate a click on buttons.
+
+### Fallbacks & browser support for `:has()`
+
+Baseline status for :has(): Widely available. It's been Baseline since 2023-12-19.
+Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 121 (Dec 2023), and Safari 15.4 (Mar 2022).
+
+If targeting browsers without `:has()`, add a class to each menu popover instead of selecting `[popover]:has(> [focusgroup~="menu"])`.
+
+### Fallbacks & browser support for `sign()`
+
+Baseline status for abs() and sign(): Newly available. It's been Baseline since 2025-06-26.
+Supported by: Chrome 138 (Jun 2025), Edge 138 (Jun 2025), Firefox 118 (Sep 2023), and Safari 15.4 (Mar 2022).
+
+If your Baseline target lacks `sign()`, skip `--bridge-side` and pick the edge and the apex nudge with `clamp()`: a large multiplier pushes `--pointer-x` past either bound, so the result is one end or the other.
+
+```css
+@supports not (width: calc(sign(1px) * 1px)) {
+ [data-bridge]::before {
+ --bridge-edge: clamp(100vw, 50% + var(--pointer-x) * 1e6, 100% - 100vw);
+ --bridge-apex: calc(100vw + var(--pointer-x) + clamp(-1 * var(--bridge-slack), var(--pointer-x) * 1e6, var(--bridge-slack)));
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-components/breadcrumbs.md b/skills/modern-web-guidance/guides/ui-components/breadcrumbs.md
new file mode 100644
index 0000000..9d6bb15
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/breadcrumbs.md
@@ -0,0 +1,168 @@
+# Build breadcrumbs
+
+Breadcrumbs show where the user is in a site hierarchy and link to each ancestor page.
+
+This is not for switching between views of the same page (tabs) or for site-wide navigation (a navbar).
+
+## 1. Semantics
+
+- Wrap the trail in `<nav aria-label="Breadcrumbs">` containing an ordered list (`<ol>`) of `<li>` items, each holding an `<a>`. Order conveys hierarchy, so use `ol`, not `ul`.
+- Give each `<nav>` a unique label if a page has several landmarks (e.g. "Breadcrumbs").
+- Mark the current page, the last item, as a link with `aria-current="page"`. Keep it a link (not plain text) so the trail structure stays consistent.
+- Dividers are decorative. Do not put them in the markup as text. Generate them in CSS with an empty alt so they stay out of the accessibility tree:
+
+```css
+/* The empty alt text after the slash hides the divider from screen readers; li + li skips the first item */
+.breadcrumb > ol > li + li::before { content: "/" / ""; }
+```
+
+- A styled character (`/`, `›`, `>`) generated as above is the simplest divider. For an icon divider such as a chevron, render it the way the codebase renders icons and keep it decorative; see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`).
+
+## 2. Styling
+
+- Lay out with `display: flex; flex-wrap: wrap; align-items: center; gap` on the `<ol>`; reset list styles.
+- Whatever the visual style, the trail must read as a path: each step visibly follows the previous one through a separator (slash or chevron) or an arrow or slant shape. Plain links with a separator are the default and the safest choice.
+- **DO NOT** drop the separator in chip-like styles. Pills, tags and a segmented bar without one look like tabs or filters (items on the same level), not a hierarchy. Plain text with no divider is also weak, since order is then the only cue; avoid it.
+- Choose a visual variant:
+ - **Plain (slash or chevron):** use when the trail should stay visually quiet. Underline links at rest, or at least on hover and focus, so they never rely on color alone.
+ - **Bar:** one bordered, segmented container with `overflow: clip`; use when segments need large, clear touch targets. Keep a separator in each segment after the first. A bar must not wrap: when its segments no longer fit on one row, stack it in a column in a container query set just above the bar's natural width (measure it and round up, so it stacks only when it would not fit), with compact rows (smaller block padding), separated by a 1px `border-block-start` and the chevron turned to point down and use a fixed `border-radius` for a joined pill, since `999px` becomes an oval once it grows tall. For a joined pill, round the container (`border-radius: 999px`) and separate segments with a 1px `border-inline-start` and no gap. Give the current page's `<li>` the same background as its link, so the chevron outside the link does not sit on the bar's background. Round the container, not the individual links, so the clip handles the end caps, and give the end links the same end radius so an inset focus ring follows the rounded ends instead of being cut off.
+ - **Pills / tags:** use rounded or shaped links when the trail is a prominent control, with a separator between them. Show backgrounds only on hover for tags.
+- Style the current page distinctly (weight, color) and non-current links with a hover state.
+- Custom palettes must meet WCAG AA contrast (4.5:1 for text) for links, hover, and the current page against their actual backgrounds (e.g. dark red on light gray). Keep a non-color cue on the current page, such as font weight.
+- Provide a clear `:focus-visible` outline that has a contrast of at least `3:1` with the background color. For shaped or clipped segments use a negative `outline-offset` or a background/color change, since outlines get clipped.
+- Lift the focused link above its neighbors (`position: relative; z-index: 1` on `a:focus-visible`). Neighbors that overlap it (shaped segments) are painted later and cover an outside ring.
+- In `forced-colors: active`, restore borders and an underline on `[aria-current="page"]` since backgrounds are removed. An icon divider drawn as a masked background also needs `forced-color-adjust: none` and a system color such as `CanvasText`, since forced colors replaces the background.
+
+### Shaped segments
+
+Pick the simplest technique that produces the shape, and use **one** shape per trail. The snippets are alternatives, not meant to be combined.
+
+- Selectors are illustrative; use your own hook (`.breadcrumb` here). Scope to `> ol > li > a`.
+- Make the slant or point size responsive with `clamp()` and container units (`cqi`).
+- Pair state colors with the shape: hover and current-page styles must use background or text color, not border color. Keep the focus style visually distinct from hover.
+- Use a negative `outline-offset` for focus, since outside outlines are covered by neighbors.
+
+#### Overlapping segments
+
+Overlapping segments communicate hierarchy even without a separator. Pull each segment under the previous one with a negative inline margin, and stack them in reverse source order so each earlier segment sits above the next. `sibling-index()` and `sibling-count()` make this possible without per-item rules:
+
+```css
+.breadcrumb > ol > li { position: relative; z-index: calc(sibling-count() - sibling-index()); }
+/* The focused segment sits above every other segment (the li is the stacking context, so lift it, not the link) */
+.breadcrumb > ol > li:has(> a:focus-visible) { z-index: calc(sibling-count() + 1); }
+```
+
+#### Simple irregular shapes (`corner-shape`)
+
+Prefer `corner-shape: bevel` with an irregular `border-radius` for parallelograms and arrows. It has better browser support than `border-shape` and keeps normal border flexibility (per-side widths, colors and styles), whereas `border-shape` needs explicit inner and outer shapes or is limited to a uniform stroke. Use logical corner properties so RTL mirrors automatically; no `:dir(rtl)` rule is needed.
+
+Slant (`/`): bevel the start-start and end-end corners with a horizontal radius of the slant and a vertical radius of 100%.
+
+Arrow (`>`): bevel both end corners with a horizontal radius of the point and a vertical radius of 50%. Overlap the next segment so the tip of each segment covers the flat start edge of the next.
+
+```css
+.breadcrumb { --slant: clamp(.4rem, 2cqi, .75rem); }
+.breadcrumb > ol, .breadcrumb > ol > li { gap: 0; }
+.breadcrumb > ol > li > a {
+ display: block;
+ corner-shape: bevel;
+ /* Extra inline padding equal to the slant keeps text out of the angled corners */
+ padding: .55rem calc(var(--slant) + .8rem);
+}
+/* The shape shows direction, so drop the separator */
+.breadcrumb > ol > li + li::before { content: none; }
+
+/* SLANT ONLY: leans like "/" in LTR and "\" in RTL */
+.breadcrumb > ol > li > a {
+ border-start-start-radius: var(--slant) 100%;
+ border-end-end-radius: var(--slant) 100%;
+}
+/* Overlap by the slant, minus a small visible gap (example .25rem), so the angled edges run parallel */
+.breadcrumb > ol > li + li { margin-inline-start: calc(.25rem - var(--slant)); }
+
+/* ARROW ONLY: tip on the end side; a contrasting segment border separates the overlapped edges */
+.breadcrumb > ol > li > a {
+ border-start-end-radius: var(--slant) 50%;
+ border-end-end-radius: var(--slant) 50%;
+}
+.breadcrumb > ol > li + li { margin-inline-start: calc(var(--slant) * -1); }
+```
+
+#### Fully irregular shapes (`border-shape`)
+
+Use `border-shape` only for shapes `corner-shape` cannot make, such as a notched arrow with a concave leading edge. Define the polygon in a custom property (`--shape`) and apply it with `border-shape` so borders and focus outlines follow the shape. Polygons are physically directional and logical properties don't flip `polygon()` coordinates, so each shape needs an explicit `:dir(rtl)` mirror.
+
+```css
+/* The first item drops the inner notch vertex so its leading edge stays flat */
+.breadcrumb > ol > li > a {
+ --shape: polygon(0 0, calc(100% - var(--point)) 0, 100% 50%, calc(100% - var(--point)) 100%, 0 100%, var(--point) 50%);
+ padding: .55rem calc(var(--point) + .8rem);
+ border-shape: var(--shape);
+}
+.breadcrumb > ol > li:first-child > a {
+ --shape: polygon(0 0, calc(100% - var(--point)) 0, 100% 50%, calc(100% - var(--point)) 100%, 0 100%);
+}
+/* Overlap by slightly less than --point so the notch and tip interlock */
+.breadcrumb > ol > li + li { margin-inline-start: calc(.25rem - var(--point)); }
+/* RTL mirror: swap 0 with 100% and calc(100% - var(--point)) with var(--point) in each x coordinate */
+.breadcrumb:dir(rtl) > ol > li > a {
+ --shape: polygon(100% 0, var(--point) 0, 0 50%, var(--point) 100%, 100% 100%, calc(100% - var(--point)) 50%);
+}
+.breadcrumb:dir(rtl) > ol > li:first-child > a {
+ --shape: polygon(100% 0, var(--point) 0, 0 50%, var(--point) 100%, 100% 100%);
+}
+```
+
+## 3. Optional UX enhancements
+
+These are optional. Implement them only when the trail needs them, and choose the implementation yourself.
+
+- **Sibling menus:** when ancestors have meaningful siblings (e.g. docs sections), let an ancestor expose its siblings in a menu. Keep the ancestor link navigating and put the toggle in a separate button, never inside the `<a>`. For menu mechanics, see `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`).
+- **Long trails:** collapse the middle of a trail with more than 3 items on narrow containers instead of letting it wrap, keeping the first item and the last two. Put the hidden links in a popup opened from a "…" button, and keep the full trail when script is unavailable.
+- **Long labels:** keep every item on one line and never truncate the current page. See `single-line-overflow` (via `npx -y modern-web-guidance@latest retrieve "single-line-overflow"`) for techniques for truncating ancestor labels and revealing the full label on demand without UX friction.
+
+## Fallback strategy
+
+### `corner-shape`
+
+Browser support for corner-shape: Limited availability.
+Supported by: Chrome 139 (Aug 2025) and Edge 139 (Aug 2025).
+Unsupported in: Firefox and Safari.
+
+- Rounded corners are not an acceptable fallback for slants and arrows. Keep plain bordered rectangular segments with a separator (`li + li::before`) as the base style, and put everything from the shape snippets that makes the shape (`corner-shape`, the radii, the padding, the overlap margins and `content: none` on the separator) inside `@supports (corner-shape: bevel)`, so unshaped segments neither overlap nor lose their separator.
+
+### `sibling-index()` and `sibling-count()`
+
+Baseline status for sibling-count() and sibling-index(): Newly available. It's been Baseline since 2026-08-18.
+Supported by: Chrome 138 (Jun 2025), Edge 138 (Jun 2025), Firefox 154 (Aug 2026), and Safari 26.2 (Dec 2025).
+
+- Without support, later segments paint on top: slants are unaffected, but arrow tips are hidden. Put the stacking rules in `@supports (z-index: sibling-index())`, and gate the arrow shape on both `corner-shape` and `sibling-index()` so it stays plain with a separator otherwise:
+
+```css
+@supports (corner-shape: bevel) and (z-index: sibling-index()) {
+ /* Arrow-only shape, overlap and stacking rules from above */
+}
+```
+
+### `border-shape`
+
+Browser support for border-shape: Limited availability.
+Supported by: Chrome 147 (Apr 2026) and Edge 147 (Apr 2026).
+Unsupported in: Firefox and Safari.
+
+- Use `clip-path: var(--shape)` with the same polygon as the base style, and enhance inside `@supports (border-shape: polygon(0 0, 100% 0, 100% 100%))` by setting `clip-path: none` and applying `border-shape`.
+- `clip-path` clips borders and outlines, so under the fallback use a color/background change plus negative `outline-offset` for focus instead of an outside outline.
+- `clip-path` also cuts the slanted sides off a border, and `forced-colors: active` removes the background that draws the shape, so a clipped segment loses its outline. Under forced colors, drop the clip and use plain bordered segments with a text separator so the trail still reads as a path:
+
+```css
+@media (forced-colors: active) {
+ /* Only without border-shape: with it, the border follows the shape and needs no change */
+ @supports not (border-shape: polygon(0 0, 100% 0, 100% 100%)) {
+ .breadcrumb > ol > li > a { clip-path: none; border: 2px solid LinkText; }
+ .breadcrumb > ol > li + li { margin-inline-start: 0; } /* undo the shape overlap */
+ .breadcrumb > ol > li + li::before { content: "›" / ""; } /* the shape no longer shows direction */
+ }
+}
+```
+
+- The trail remains fully functional; only borders and outlines differ.
diff --git a/skills/modern-web-guidance/guides/ui-components/carousel.md b/skills/modern-web-guidance/guides/ui-components/carousel.md
new file mode 100644
index 0000000..a7c8cd7
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/carousel.md
@@ -0,0 +1,176 @@
+# Build a carousel
+
+Build a carousel for a finite set of related items. Use native scrolling and CSS scroll snap as the foundation; add HTML previous/next and marker controls, with a small script for wiring them and for status updates. This keeps content and basic scrolling usable without JavaScript.
+
+## Structure and accessibility
+
+- Use a named `region` with `aria-roledescription="carousel"` when the carousel is a meaningful page section. Give each slide `role="group"`, `aria-roledescription="slide"`, and an `aria-label` that includes its position (for example, `aria-label="2 of 4"`). Write the labels in the markup, localized with the rest of the page; if slides change at runtime, regenerate them from the same localized strings. The position is the slide's place in the original sequence, not its current visual position. Keep slide content available to assistive technology.
+- Give every control a clear accessible name: use a native `<button>` with a text or `aria-label` name, not an unlabeled chevron.
+- Announce the current slide in a visually hidden polite status region after scrolling settles. Update it whenever the visible slide changes, whether through the buttons, the markers, or direct scrolling, so assistive technology receives feedback.
+
+## Scrolling and controls
+
+- Make the track natively scrollable and snap slides on its scrolling axis. For horizontal carousels, arrange slides in a row and use the inline axis; for vertical carousels, use a column and the block axis.
+- Use HTML `<button>` elements for previous/next controls and one marker button per slide for direct navigation, in every browser. Do not use `::scroll-button()` or `::scroll-marker` for now.
+
+- Keep controls visible, operable, and clearly focused with `:focus-visible`. Loop previous/next controls continuously from the last slide to the first and back by default when there are at least three slides (see Looping); disable them at the ends only when finite navigation is requested or `sibling-index()` is unsupported. Preserve native keyboard behavior; do not intercept keys from links, form fields, or buttons. Add custom key handling only for a defined interaction need, and avoid overriding nested controls.
+
+## Related patterns
+
+- For styling the active slide itself, see `carousel-snap-highlights` (via `npx -y modern-web-guidance@latest retrieve "carousel-snap-highlights"`).
+- For a continuous progress indicator instead of discrete markers, see `scroll-progress-indicator` (via `npx -y modern-web-guidance@latest retrieve "scroll-progress-indicator"`).
+- For scroll-driven slide effects, see `carousel-slide-effects` (via `npx -y modern-web-guidance@latest retrieve "carousel-slide-effects"`).
+- For synchronizing other UI with snap events, see `scroll-snap-state-sync` (via `npx -y modern-web-guidance@latest retrieve "scroll-snap-state-sync"`).
+
+## Example: horizontal carousel
+
+This example uses full-width horizontal slides. Adapt the slide sizing for a peek layout or use the block axis for a vertical carousel. Give each marker a name that identifies its destination. The CSS below is split by concern, and only the parts that are easy to get wrong are shown; everything else is described in prose. Adapt dimensions, spacing, and colors to the design.
+
+```html
+<section class="carousel" aria-roledescription="carousel" aria-label="Featured products">
+ <div class="carousel-controls">
+ <button type="button" data-direction="previous">Previous slide</button>
+ <button type="button" data-direction="next">Next slide</button>
+ </div>
+
+ <div class="carousel-track" tabindex="0" role="group" aria-label="Slides">
+ <div role="group" aria-roledescription="slide" aria-label="1 of 3"
+ data-marker-name="Go to slide 1">
+ <h3>Product one</h3>
+ </div>
+ <div role="group" aria-roledescription="slide" aria-label="2 of 3"
+ data-marker-name="Go to slide 2">
+ <h3>Product two</h3>
+ </div>
+ <div role="group" aria-roledescription="slide" aria-label="3 of 3"
+ data-marker-name="Go to slide 3">
+ <h3>Product three</h3>
+ </div>
+ </div>
+
+ <p class="visually-hidden" role="status" aria-live="polite"></p>
+
+ <nav class="carousel-markers" aria-label="Choose a slide"></nav>
+</section>
+```
+
+### Track and snapping
+
+The track is a flex row that scrolls on the inline axis and snaps to slides. Each slide fills the track and snaps to center.
+
+```css
+.carousel-track {
+ display: flex;
+ gap: 1rem; /* example value */
+ overflow-x: auto;
+ /* mandatory so the track always rests on a slide, which the settled-scroll status relies on */
+ scroll-snap-type: x mandatory;
+}
+
+.carousel-track > * {
+ flex: 0 0 100%; /* one slide per view; use a smaller basis for a peek layout */
+ scroll-snap-align: center;
+}
+```
+
+### Controls
+
+Position the Previous and Next buttons over the track's start and end edges (a `position: absolute` container with a `z-index` so slides don't cover them, and `pointer-events: none` on the container with `pointer-events: auto` on the buttons so the track stays scrollable between them). Build the marker buttons from the slides' `data-marker-name` values, and style the active one with `[aria-current="true"]`.
+
+```css
+.carousel-markers button[aria-current="true"] {
+ background: #0a5; /* example color; any clear contrast with the other markers works */
+}
+```
+
+### Supporting styles
+
+Write these to fit the design:
+
+- Style the markers as dots in a centered flex row with a gap, using the pointer cursor.
+- Show a clear `:focus-visible` outline on the control and marker buttons.
+- Set `touch-action: manipulation` on the track and the control buttons, so quick taps on them do not trigger double-tap zoom on touch devices.
+- Keep the status region visually hidden without removing it from the accessibility tree.
+- Enable `scroll-behavior: smooth` on the track only inside `@media (prefers-reduced-motion: no-preference)`.
+
+## Fallback strategies
+
+The controls are plain HTML, so the fallbacks below only cover the platform features that the script and CSS rely on. Scrolling and snap behavior remain native, and small amounts of script add the controls' behavior and status updates.
+
+### Scrolling and completion
+
+Baseline status for scroll-behavior: Widely available. It's been Baseline since 2022-03-14.
+Supported by: Chrome 61 (Sep 2017), Edge 79 (Jan 2020), Firefox 36 (Feb 2015), and Safari 15.4 (Mar 2022).
+
+Smooth scrolling is optional. The example enables it only when reduced motion is not requested.
+
+Baseline status for scrollend: Newly available. It's been Baseline since 2025-12-12.
+Supported by: Chrome 114 (May 2023), Edge 114 (Jun 2023), Firefox 109 (Jan 2023), and Safari 26.2 (Dec 2025).
+
+If `scrollend` is unavailable, use a debounced `scroll` listener to run the settled-scroll handler. Run the initial marker, button, and parking sync once on load, leaving the polite status region empty until user-initiated scrolling settles so page load is not interrupted.
+
+Browser support for Scroll snap events: Limited availability.
+Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
+Unsupported in: Firefox and Safari.
+
+The carousel does not depend on snap events. If they are unavailable, use settled-scroll tracking for status; use `scrollsnapchange` only when other UI must follow the browser-selected snap target.
+
+### Scroll snap
+
+Baseline status for Scroll snap: Widely available. It's been Baseline since 2020-01-15.
+Supported by: Chrome 69 (Sep 2018), Edge 79 (Jan 2020), Firefox 68 (Jul 2019), and Safari 11 (Sep 2017).
+
+The track remains natively scrollable with touch, pointer, and keyboard input. JavaScript adds the controls' behavior and announcements without replacing basic scrolling. Place the script in a `<script type="module">` element so it runs after the document has been parsed.
+
+### Looping
+
+Baseline status for sibling-count() and sibling-index(): Newly available. It's been Baseline since 2026-08-18.
+Supported by: Chrome 138 (Jun 2025), Edge 138 (Jun 2025), Firefox 154 (Aug 2026), and Safari 26.2 (Dec 2025).
+
+Wrap the parking rule in `@supports` for `sibling-index()`. Without support, leave the carousel as a finite list: skip the parking and keep disabling the controls at the ends.
+
+### Scroll-driven effects
+
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Treat slide effects as optional enhancements and keep them inside `@media (prefers-reduced-motion: no-preference)`. The carousel's navigation and current-slide feedback must not depend on them.
+
+## Controls and status updates
+
+Update the active marker as the track scrolls (throttled to one update per animation frame) so the dots keep pace with the visible slide, and run announcements and button state after scrolling settles. Measure only the carousel's scrolling axis.
+
+Write a small script that adapts to your markup and covers these requirements:
+
+- **Wire the HTML controls.** On a Previous or Next click, find the current slide from the track's scroll position along its scrolling axis, then scroll the track to the adjacent slide's snap position in visual order (which differs from DOM order when looping), for example with `track.scrollBy()` using that slide's offset from the track's center. Do not scroll by a fixed viewport width, keep a separate index that can drift from the real scroll position, or use `scrollIntoView()` without limiting it to the track, which can scroll the page. Create one named marker button per slide that scrolls the track to that slide. Keep the Previous and Next buttons before the track in DOM order.
+- **Track the current slide** along the carousel's scrolling axis, for horizontal or vertical layouts.
+- **Update the active marker live.** From a `scroll` listener throttled with `requestAnimationFrame`, compute the nearest slide and set the active marker's `aria-current="true"` immediately, and also set it from the pending target the moment a marker or Previous/Next button is clicked, so the dots change when the user decides instead of after the slide moves. Skip the write when the current slide is unchanged, and skip the listener entirely while a click or key press has a pending target, because recomputing every frame during a scripted smooth scroll makes Safari stutter.
+- **Update the rest after scrolling settles**, from a single handler driven by the settled scroll position: update the buttons' disabled state (and slide parking when looping), and announce "Slide N of M" in the status region only when the settled slide changes from the previously settled slide (keeping initial load and compensating park scrolls silent). Controls only initiate scrolling; they never update state directly.
+- **Settle on `scrollend`**, with a debounced `scroll` listener only where `scrollend` is unsupported. Do not run two settle handlers, and do not reorder or re-scroll the track (such as when parking a slide) while a scroll is still in flight, because that cancels it.
+- **Resolve clicks from a pending target.** Make rapid previous/next clicks build on the slide already being scrolled to, not on the nearest slide, and clear the target when scrolling settles. Ignore a `scrollend` that arrives after the next scroll has started, because acting on it (such as parking) cancels that scroll.
+- **Respect reduced motion** for any smooth scrolling.
+
+## Looping (continuous navigation)
+
+Loop previous and next navigation from the last slide to the first and back by keeping the track endless instead of disabling controls at the ends (unless the carousel has fewer than three slides or finite navigation is requested). Do not clone slides or move them in the DOM, which conflicts with frameworks and duplicates content for assistive technology. Instead, park an end slide beside the current one with CSS `order`, and only when the carousel is at or one step from that end. Parking one step early puts the neighbor in place before scrolling reaches an end, so the previous and next buttons never disable mid-scroll. The track then always has a neighbor on both sides, and keyboard scrolling, touch, and snapping all keep working. Only the first and last slides ever get `order`. Because parking starts one step before an end, a short carousel can have an end slide parked at every position (with 4 slides, always; with 3, both ends at the middle slide). DOM order applies unchanged only at positions that are more than one step from both ends, which needs 5 or more slides.
+
+- Keep a `--current` custom property on the track: the zero-based index of the current slide. Do not give it a default in CSS: while it is undefined, `order` falls back to 0, so no slide is parked and the carousel starts on the first slide without JavaScript. The script sets it on load. Park the last slide before the first (`order: -1`) when `--current` is `0` or `1`, and park the first slide after the last (`order: 1`) when `--current` is the last or second-to-last index. Set `order` only on the first and last slides (`:first-child` and `:last-child`), not on every slide. `sibling-count()` is needed to find the last indexes. The formulas below are the part that is easy to get wrong.
+- When scrolling settles, update `--current` from the scroll position. If the parking changes, measure the current slide's offset along the scrolling axis before and after, then instantly scroll by the difference in the same task so the change is invisible. Turn scroll snapping off (`scroll-snap-type: none`) around the reorder and the compensating scroll and restore it afterward, because some browsers otherwise re-snap to another slide and keep scrolling. Also lock overflow on the scrolling axis (`overflow-x: hidden`, or `overflow-y: hidden` for vertical) for the same step and restore it two animation frames later: Safari on iOS otherwise paints the reordered layout for a frame before the compensating scroll lands, which flickers. Restoring it immediately breaks looping, so keep the delay. This also applies when a parked slide is released after the user leaves an end slide.
+- Set `inert` on the parked slide while it is parked, and clear it when it becomes the current slide. It is a visual-only neighbor, so its content must not be reachable by keyboard or assistive technology out of sequence.
+- Looping needs at least three slides. Because the compensation is measured, slides may differ in size.
+- The previous/next controls and the status calculation must work from visual order, not DOM sibling order. Per-slide labels ("2 of 4") and the status region use each slide's original index, which does not change when slides are parked. Do not renumber slides when `--current` changes.
+- Keep `scroll-behavior: smooth` inside `prefers-reduced-motion: no-preference` for user navigation; only the compensating scroll is instant.
+
+```css
+/* The first slide parks after the last while --current is the last or second-to-last index. */
+.carousel-track > :first-child {
+ order: clamp(0, var(--current) - (sibling-count() - 3), 1);
+}
+
+/* The last slide parks before the first while --current is 0 or 1. */
+.carousel-track > :last-child {
+ order: calc(-1 * clamp(0, 2 - var(--current), 1));
+}
+```
+
+Accessibility trade-offs: only the first and last slides are ever parked and a parked slide is inert, so Tab order and the accessibility tree match what the user can interact with.
diff --git a/skills/modern-web-guidance/guides/ui-components/checkbox.md b/skills/modern-web-guidance/guides/ui-components/checkbox.md
index 53e8ab2..6b828c1 100644
--- a/skills/modern-web-guidance/guides/ui-components/checkbox.md
+++ b/skills/modern-web-guidance/guides/ui-components/checkbox.md
@@ -107,6 +107,8 @@ selectAll.indeterminate = true;
- **DO** use `:focus-visible` rather than `:focus` to style focus indicators on custom checkboxes so a distinct outline appears for keyboard navigation without showing on pointer clicks.
- **DO NOT** use `outline: none` or hide focus indicators on checkboxes.
+- **DO** ensure the contrast of focus indicators has a contrast of at least `3:1` with the background color
+- **DO** ensure the color for the checked and indeterminate state has a contrast of at least `3:1` with the background color
- **DO** ensure the checkbox or its wrapping `<label>` provides an interactive hit target of at least `44px x 44px` while keeping the visual checkbox box sized in relative units:
```css
label {
diff --git a/skills/modern-web-guidance/guides/ui-components/copy-button.md b/skills/modern-web-guidance/guides/ui-components/copy-button.md
new file mode 100644
index 0000000..593242d
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/copy-button.md
@@ -0,0 +1,219 @@
+# Copy button
+
+Build a button that copies the text of another element (code block, inline value, read-only field) or the current selection. Declare the target with Invoker Commands (`command` + `commandfor`) instead of per-button JavaScript wiring, and write with the Async Clipboard API.
+
+## Implementation
+
+### 1. Markup
+
+```html
+<!-- Custom commands MUST start with "--". commandfor is the id of the element whose text is copied. -->
+<span class="copy"> <!-- positioning context for the bubble -->
+ <!-- aria-label names the content being copied; several bare "Copy" buttons are indistinguishable to screen readers -->
+ <button type="button" class="copy-button" command="--copy" commandfor="snippet" aria-label="Copy CSS code">
+ <!-- Decorative icon, rendered however the codebase renders icons -->
+ <span class="icon" aria-hidden="true"></span>
+ </button>
+ <!-- The confirmation bubble IS the live region. Keep it empty until a copy, and outside the button:
+ a button's children are presentational, so a live region inside one is not reliably announced -->
+ <span class="tip" role="status"></span>
+</span>
+<pre><code id="snippet">…</code></pre>
+```
+
+- Use `type="button"` so the button never submits a form.
+- Size the button at least 24×24 CSS px with `min-inline-size`/`min-block-size` (not `inline-size`/`block-size`), so content can grow the target but never shrink it.
+- Name an icon-only button with `aria-label`. If the button shows visible text, that text is the name; do not add an `aria-label` that differs from it.
+- Render the icon with whatever the codebase uses for icons (see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`)) and mark it decorative; the button's accessible name comes from `aria-label`, not the icon.
+
+### 2. Copying logic
+
+Put the copy logic in one function so the native and fallback paths share it.
+
+```js
+let selectedText = ''; // set by the optional selection popover (step 3)
+
+async function copy(button, target, command = '--copy') {
+ // Form controls expose text via .value; innerText (unlike textContent) keeps rendered line breaks
+ const text = command === '--copy-selection'
+ ? selectedText
+ : target.matches('input, textarea') ? target.value : target.innerText.trim();
+ if (!text) return;
+ try {
+ await navigator.clipboard.writeText(text);
+ report(button, true); // see Feedback below
+ } catch {
+ report(button, false); // clipboard access can be denied: show the failure too, not only announce it
+ }
+}
+
+// `command` events do not bubble: listen in the capture phase on document.
+// event.source is the clicked button; event.target is the commandfor element.
+document.addEventListener('command', (event) => {
+ if (event.command.startsWith('--copy')) copy(event.source, event.target, event.command);
+}, true);
+```
+
+- **One element for sighted and screen reader users:** `report()` sets `data-copied` (or `data-failed`) on the button and writes the message into the bubble, which is both the visible feedback and the live region. Sighted and screen reader users then get the same message for both outcomes. Keep messages short ("Copied", "Copy failed").
+- **Show and hide the bubble with `opacity`,** not `display: none` or `visibility: hidden`, which take it out of the accessibility tree so the text is not announced.
+- **Clean up:** after a short timeout, remove the state attributes and clear the bubble's text, so no stale "Copied" is left for screen reader browse mode.
+- **Not color alone:** swap the icon (copy to check) on success and use the bubble text for both outcomes.
+- **Repeat clicks:** clear the pending timeout and restart the animation instead of stacking timers. DO NOT disable the button while showing feedback: copying is idempotent, and disabling drops keyboard focus, announces a misleading unavailable state, and blocks retrying after a failure.
+- **Reduced motion:** under `prefers-reduced-motion: reduce`, replace icon and bubble animations with an opacity fade.
+
+```js
+const timers = new WeakMap();
+
+function report(button, ok) {
+ const tip = button.nextElementSibling; // the role="status" bubble
+ clearTimeout(timers.get(button));
+ button.removeAttribute('data-copied');
+ button.removeAttribute('data-failed');
+ const message = ok ? 'Copied' : 'Copy failed';
+ tip.textContent = '';
+ void button.offsetWidth; // restart the CSS animation
+ button.setAttribute(ok ? 'data-copied' : 'data-failed', '');
+ requestAnimationFrame(() => (tip.textContent = message));
+ timers.set(button, setTimeout(() => { // 2000ms is an example value
+ button.removeAttribute('data-copied');
+ button.removeAttribute('data-failed');
+ tip.textContent = '';
+ }, 2000));
+}
+```
+
+### 3. Copy the current selection (optional)
+
+Add this only for long prose where users want a floating button on selection. Skip it for code blocks, inline values, and fields.
+
+- Use a `popover="manual"` element (not light-dismissed, so the selection survives) containing a button with `command="--copy-selection" commandfor="<container id>"`.
+- Show it on `selectionchange` (debounced; wait for `pointerup` while dragging) only when the selection is non-collapsed and inside the container. A triple-click ends at the start of the next element, so do not require the end node to be inside: clip the range's end to the container and accept it when the clipped text equals the selected text. Copy and position from the clipped range, using its `getBoundingClientRect()`: centered on the inline axis and above the selection on the block axis, so it never covers selected text. Only enable the popover when `matchMedia('(pointer: fine)').matches`: touch browsers already offer Copy in their native selection menu, which the popover would duplicate and collide with.
+- Assign the selected text to `selectedText` when showing the popover; `copy()` reads that saved string for `--copy-selection`; interacting with the button can collapse the live selection.
+- Call `preventDefault()` on the popover's `pointerdown` to keep the selection. This also stops the button from taking focus on click or tap, so `:focus-within` cannot tell you that a press is in progress. Set a flag on the popover's `pointerdown` and, while it is set, do not hide the popover even if the selection collapses (some touch browsers clear it anyway). Clear the flag and re-check when the copy feedback ends (and on `pointercancel`). Otherwise, hide it on `Escape`, and when the selection collapses unless keyboard focus is inside the popover (re-check when focus leaves it).
+- DO NOT hide the popover when the copy feedback timeout ends: a keyboard user's focus is on its button, and hiding it drops focus to the page, so the next `Tab` starts from the top. If `Escape` hides it while focus is inside, first move focus to the container: set `tabindex="-1"` on it just before the move and remove it on `blur`. Do not leave it in the markup, because a focusable container makes `Tab` skip the copy button in Firefox after a click in the text.
+
+### 4. Repeated copyable elements (optional)
+
+When a page repeats copyable elements (code blocks, list rows, token or ID cells), a visible button on each one adds noise. Keep the button hidden until the element is hovered, reveal it for keyboard users too, and never make it hover-only.
+
+```css
+/* Touch devices (no hover): the button stays visible, so keep it in flow where it cannot cover content */
+.copyable { display: flex; align-items: start; gap: .5rem; }
+.copyable .copy { flex: none; order: 1; }
+
+/* Only hide where hover exists; the overlay is then revealed on demand */
+@media (hover: hover) {
+ .copyable { display: block; position: relative; }
+ .copyable .copy { position: absolute; inset-block-start: .5rem; inset-inline-end: .5rem; } /* .copy is the bubble's positioning context, so move it, not the button */
+ .copyable .copy-button { opacity: 0; transition: opacity .15s; }
+ .copyable:hover .copy-button,
+ .copyable:focus-within .copy-button,
+ .copyable .copy-button:focus-visible,
+ .copyable .copy-button[data-copied],
+ .copyable .copy-button[data-failed] { opacity: 1; }
+}
+```
+
+- Hide with `opacity` only. `display: none` and `visibility: hidden` remove the button from the tab order, so keyboard users could never reach it.
+- Reveal on `:focus-within` of the container, as well as `:hover`, so the button shows when focus is on it or on focusable content in the block (such as a scrollable `<pre tabindex="0">`).
+- Keep it visible on `(hover: none)` devices, where there is no hover to reveal it. Lay it out in flow beside the content there so it never covers it.
+- Keep it visible while feedback shows (`data-copied` / `data-failed`), so the state does not vanish when the pointer leaves.
+- Keep the button's 24×24 px minimum size and its accessible name; a hidden-by-opacity button is still announced by screen readers.
+- DO NOT add `aria-hidden`, `inert` or `hidden` to the button to "hide" it, and do not toggle them on hover. Screen reader users (VoiceOver included) must be able to reach it with no hover, and focus moving onto it (including a screen reader cursor that moves focus) is what makes it visible.
+- Add `padding-inline-end` on the `<pre>` so the button clears the code at rest. On a horizontally scrolling `<pre>`, that padding is only reached at the end of the scroll range, so long lines can pass under the button while scrolling. Give the button a mostly opaque background and a visible border so it stays legible over code, rather than reserving a permanent margin that narrows the code area on small screens.
+
+## Fallbacks and browser support
+
+### Invoker Commands
+
+Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
+Supported by: Chrome 135 (Apr 2025), Edge 135 (Apr 2025), Firefox 144 (Oct 2025), and Safari 26.2 (Dec 2025).
+
+If your Baseline target does not include Invoker Commands, keep the same markup and add a click listener that calls the same `copy()` function. This is a short, robust fallback (progressive enhancement of the same experience):
+
+```js
+// Detect on the interface, not an instance
+if (!('CommandEvent' in window)) {
+ // Resolve the target from commandfor, as the browser does for command events
+ document.addEventListener('click', (event) => {
+ const button = event.target.closest('button[command^="--copy"]');
+ if (!button) return;
+ const target = document.getElementById(button.getAttribute('commandfor'));
+ if (target) copy(button, target, button.getAttribute('command')); // a missing target would throw inside copy()
+ });
+}
+```
+
+Register only one of the two paths so a click never copies twice.
+
+### Async Clipboard
+
+Baseline status for the api.Clipboard.writeText capability: Widely available. It's been Baseline since 2020-03-24.
+Supported by: Chrome 66 (Apr 2018), Edge 79 (Jan 2020), Firefox 63 (Oct 2018), Safari 13.1 (Mar 2020), and Safari iOS 13.4 (Mar 2020).
+
+`navigator.clipboard` is only available in secure contexts (`https:` or `localhost`), and the write is rejected when permission is denied. `copy()` already covers both: a missing `navigator.clipboard` throws inside the `try`, so the failure message is shown and announced. Serve the page over HTTPS: that is the real fix.
+
+Only as a last resort, when you cannot control the protocol of the host page (for example a component embedded on third-party sites), fall back to the deprecated `document.execCommand('copy')` so copying still works for the user. It must run synchronously inside the user's click handler, so use it only when `navigator.clipboard` is missing or the write rejects:
+
+```js
+function legacyCopy(text) {
+ const field = Object.assign(document.createElement('textarea'), { value: text });
+ field.setAttribute('readonly', '');
+ field.style.cssText = 'position:fixed;inset-block-start:0;opacity:0';
+ document.body.append(field);
+ field.select();
+ try { return document.execCommand('copy'); } finally { field.remove(); }
+}
+
+// In copy(), replace the plain write with:
+try {
+ await navigator.clipboard.writeText(text);
+} catch {
+ if (!legacyCopy(text)) throw new Error('Copy failed'); // reaches the existing failure path
+}
+```
+
+Only the optional selection button (step 3) uses Popover.
+
+### Fallbacks & browser support for Popover
+
+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
+Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
+
+The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
+
+**Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
+ import("@oddbird/popover-polyfill");
+}
+```
+
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Repeated announcements (VoiceOver)
+
+VoiceOver skips a message identical to the previous one from the same region, even if the region was emptied in between. Track the last message in a variable (not by reading the bubble, which is cleared) and, when a message repeats, append a no-break space (`\u00A0`) so it differs. It is not read aloud. One page-wide value is the simplest way to track it: a message from another button's bubble gets the space too, which is harmless. Do not use `ariaNotify()` for this.
+
+```js
+let lastMessage = '';
+
+// In report(), replace `const message` with `let message`, then:
+if (message === lastMessage) message += '\u00A0'; // differs from the last one, so it is announced
+lastMessage = message;
+```
+
diff --git a/skills/modern-web-guidance/guides/ui-components/dialog.md b/skills/modern-web-guidance/guides/ui-components/dialog.md
index fbd3c21..8117413 100644
--- a/skills/modern-web-guidance/guides/ui-components/dialog.md
+++ b/skills/modern-web-guidance/guides/ui-components/dialog.md
@@ -200,27 +200,19 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
display: block;
}
```
-
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
diff --git a/skills/modern-web-guidance/guides/ui-components/hovercard.md b/skills/modern-web-guidance/guides/ui-components/hovercard.md
index 47f08b1..2f1dbf9 100644
--- a/skills/modern-web-guidance/guides/ui-components/hovercard.md
+++ b/skills/modern-web-guidance/guides/ui-components/hovercard.md
@@ -6,7 +6,7 @@ If you need plain-text, non-interactive tooltips rather than structured link pre
## 1. Triggering the hovercard
-Use the **Interest Invokers** API to trigger the hovercard. This ensures the card appears on both hover and focus, and handles accessibility wiring automatically.
+Use the **Interest Invokers** API to trigger the hovercard. This ensures the card appears on both hover and focus.
- Add the `popover="hint"` attribute to your card container. Use `hint` to avoid closing unrelated popover menus that may be open.
- Add the `interestfor` attribute to the trigger link, pointing to the card's `id`.
@@ -25,15 +25,40 @@ Use the **Interest Invokers** API to trigger the hovercard. This ensures the car
</div>
```
-You do not need to include an additional link to the content inside of the hovercard, as it is redundant to the triggering link.
+You do not need to include an additional link to the content inside of the hovercard, as it is redundant to the triggering link.
-### Accessibility built in to `interestfor`
+### Accessibility
-When you use `interestfor`, the browser handles the assistive-technology wiring for you:
+`interestfor` is specified to wire hint popovers (`popover="hint"`) for assistive technology itself, based on what the target contains. A **plain hint** (text and images only) becomes the trigger's accessible description, or its name if it has none. A **rich hint** (headings, links, or other interactive content) gets a minimum role of `tooltip`, the trigger gets `aria-expanded` and an `aria-details` relation while the hint is open, and the open hint comes right after the trigger in the tab order so keyboard users can reach its content.
-- **Implicit semantics:** A target with `popover="hint"` gains an implicit minimum role of `tooltip`. **DO NOT** set `role="tooltip"` yourself.
-- **Implicit association:** The browser implicitly associates the source element with the target via `aria-describedby` when the target is plaintext, or via `aria-details` when the target contains interactive content. **DO NOT** add `aria-describedby` or `aria-details` to the trigger.
-- **Interactive content:** Because the association switches to `aria-details` when needed, the target IS allowed to contain interactive content (e.g. a link inside an "interest card").
+Browsers and screen readers do not yet expose this consistently, so add explicit ARIA as well:
+
+- **Hint that repeats the trigger's accessible name** (e.g. an icon-only button with `aria-label="Bold"` and a "Bold" tooltip): add nothing. A description identical to the name would be read twice.
+- **Hint on a trigger with no visible label of its own** (e.g. an icon-only button without `aria-label`): `aria-labelledby` on the trigger pointing at the hint, so the hint becomes the name.
+- **Hint whose trigger also opens it on activation** (a toggletip, or any button whose only job is the hint: give it `popovertarget` with `popovertargetaction="show"`): `role="tooltip"` on the hint and `aria-expanded` on the trigger, kept in sync with the popover's `toggle` event. A description read right after "button" suggests further actions and muddles the role; the expanded state tells the user there is content to reveal and whether it is open, and pressing the button delivers it. Place the hint right after the trigger in the DOM so reading keys reach its content once it is open.
+- **Hint whose trigger does something else on activation** (a link, a button with its own action): `role="tooltip"` on the hint and `aria-describedby` on the trigger, never `aria-expanded`. A trigger announced as "collapsed" suggests `Enter` would expand it, but `Enter` navigates or acts. The hint must be something the user can afford to miss: a hovercard previews the destination, a tooltip on an action button describes the action.
+- **DO NOT** attach a hint that opens on activation to a control that already uses `aria-expanded` for something else (for example, a menu button). Give that hint its own trigger instead.
+- **DO NOT** move focus into the target when interest is shown (no `autofocus`, no `focus()` in an `interest` listener). Interest is triggered by hover or focus alone, so moving focus would fail WCAG 3.2.1 (On Focus).
+
+Not every screen reader reads descriptions when moving through the page (NVDA skips them in browse mode by design), so a hint exposed as a description must only carry content the user can afford to miss. Link previews and tooltips on action controls qualify; anything the user needs belongs in a toggletip or inline.
+
+Wire this with a short script instead of hand-authoring the attributes, so the markup stays declarative and the same rules apply to every hint. The script should:
+
+1. Run in every browser, before loading the `interestfor` polyfill, once the DOM is parsed, and expose a function that can be called again for content inserted later. Scanning upfront is required: a browse-mode screen reader user needs the attributes in place before any interaction, so wiring them lazily on `focus` or `interest` is too late, and so is waiting for the polyfill, which wires its ARIA only on `load` and adds no `role="tooltip"` to plain hints.
+2. For every `[interestfor]` trigger whose target has `popover="hint"`, normalize whitespace and compare the hint text with the trigger's accessible name (`aria-labelledby` targets, else `aria-label`, else text content including image `alt`, else `title`). Equal: do nothing. Otherwise set `role="tooltip"` on the hint if it has no role.
+3. When the trigger has no name, point `aria-labelledby` at the hint unless it already has one. Otherwise, if the trigger also opens the hint on activation (a `popovertarget` or `commandfor` naming the hint), set `aria-expanded` to the popover's current state (`:popover-open`) unless it already has `aria-expanded`, and remember which triggers the script owns; if not, point `aria-describedby` at the hint unless it already has one.
+4. Keep `aria-expanded` in sync from the popover's `toggle` event in every browser with a single capturing listener on `document`, updating every trigger with a matching `interestfor` that the script owns (the `interestfor` polyfill does not sync `aria-expanded` on plain-text hints or when a toggletip is opened via `popovertarget`).
+
+Things that are easy to get wrong:
+
+- `toggle` does not bubble. A bubbling listener on `document` never fires; use the capture phase (or a listener per popover).
+- Sync `aria-expanded` from `toggle`, not from `interest`/`loseinterest`. The popover is the source of truth: it can be closed by `Escape`, light dismiss, or another invoker, and several triggers can share one hint.
+- A hidden popover is a valid `aria-describedby` or `aria-labelledby` target. Do not force the hint open or duplicate its text to make it "visible".
+- Do not add `aria-haspopup` or a live region to any hint.
+- Do not override author ARIA: an existing `aria-describedby`, `aria-labelledby`, or `aria-expanded` on the trigger wins.
+
+> [!IMPORTANT]
+> Only use hovercards to provide supplemental information (e.g. a preview of information that can otherwise be obtained by clicking on the link), never information that is not available in any other way.
## 2. Positioning with Anchor Positioning
@@ -67,7 +92,7 @@ If users are likely to move through multiple triggers in quick succession, set t
}
```
-Use `@starting-style` to define the entry animation and `transition-behavior: allow-discrete` (along with `display` and `overlay`) to animate the exit from the top layer, gating the transitions behind `@media (prefers-reduced-motion: no-preference)`.
+Use `@starting-style` to define the entry animation and `transition-behavior: allow-discrete` (along with `display` and `overlay`) to animate the exit from the top layer, gating the transitions behind `@media (prefers-reduced-motion: no-preference)`. Declare `transition-behavior: allow-discrete` as a separate property after `transition` rather than inside the `transition` shorthand so older browsers do not ignore the entire `transition` declaration.
```css
[popover].hovercard {
@@ -96,6 +121,7 @@ Use `@starting-style` to define the entry animation and `transition-behavior: al
display,
overlay;
transition-duration: 0.4s;
+ /* Separate after transition so the shorthand doesn't reset it or fail in older browsers */
transition-behavior: allow-discrete;
}
}
@@ -198,22 +224,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
-
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -221,16 +241,18 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
+### Fallbacks & browser support for `popover="hint"`
Browser support for popover="hint": Limited availability.
Supported by: Chrome 151 (Jul 2026), Edge 151 (Jul 2026), and Firefox 153 (Jul 2026).
Unsupported in: Safari.
+The `@oddbird/popover-polyfill` package does not polyfill `popover="hint"` in browsers that already support native `popover` (`auto` and `manual`). In those browsers, the unrecognized `"hint"` value defaults to `popover="manual"` (the HTML invalid value default), so a hovercard opened via keyboard focus may remain open if a second hovercard is opened via pointer hover unless explicitly dismissed on loss of interest by the invoker.
+
### Fallbacks & browser support for Interest invokers
Browser support for Interest invokers: Limited availability.
-Supported by: Chrome 142 (Oct 2025) and Edge 142 (Oct 2025).
+Supported by: Chrome 149 (Jun 2026) and Edge 149 (Jun 2026).
Unsupported in: Firefox and Safari.
Interest invokers must be conditionally polyfilled using the `interestfor` polyfill package from NPM. Prefer bundling the polyfill over using the CDN.
@@ -239,7 +261,7 @@ Interest invokers must be conditionally polyfilled using the `interestfor` polyf
```html
<script type="module">
- if (!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")) {
+ if (!("interestForElement" in HTMLButtonElement.prototype)) {
// CDN link only used for example, prefer bundling.
await import("https://unpkg.com/interestfor@latest");
}
@@ -270,10 +292,92 @@ When using the polyfill, the CSS API changes slightly to account for the lack of
}
```
+### Fallbacks & browser support for Anchor positioning
+
Browser support for Anchor positioning: Limited availability.
Supported by: Safari 27 (Sep 2026).
Unsupported in: Chrome, Edge, and Firefox.
+Without CSS Anchor Positioning, tethered elements such as `[popover]` overlays fall back to their default user-agent placement (centered in the viewport for popovers). Depending on whether spatial tethering is required for your use case, either conditionally load the polyfill or gate your positioning rules with `@supports`.
+
+#### Option 1: Polyfill (`@oddbird/css-anchor-positioning`)
+
+When the positioned element must stay spatially tethered to its trigger in unsupported browsers, conditionally load the `@oddbird/css-anchor-positioning` package.
+
+**MANDATORY:** Feature-detect support via `CSS.supports("anchor-name: --a")` (or `"anchorName" in CSSStyleDeclaration.prototype`), and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature-detect anchor positioning support before loading the polyfill.
+if (!CSS.supports("anchor-name: --a")) {
+ import("@oddbird/css-anchor-positioning");
+}
+```
+
+Without a bundler, import from a CDN inside a `<script type="module">`:
+
+```html
+<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->
+<script type="module">
+ if (!CSS.supports("anchor-name: --a")) {
+ import("https://unpkg.com/@oddbird/css-anchor-positioning");
+ }
+</script>
+```
+
+**Polyfill caveats:**
+- **No implicit anchors:** The polyfill does not support implicit anchor associations (such as those created by `popovertarget`, `commandfor`, `interestfor`, or `showPopover({ source })`). You **MUST** set a unique explicit `anchor-name` on each trigger and a matching `position-anchor` on the positioned element.
+- **No `position-area` with `position-try-fallbacks`:** `position-area` with `position-try-fallbacks` is not supported by the polyfill. When using the polyfill on elements needing fallbacks, position elements using `anchor()` functions on inset properties (`top`, `left`, `right`, `bottom`) with `inset: auto` instead of `position-area`.
+- **Do not wrap polyfilled rules in `@supports`:** Browsers without native anchor positioning evaluate `@supports (position-area: ...)` and `@supports (anchor-name: --a)` to `false` and discard the block before the polyfill can process it.
+
+```css
+.trigger {
+ /* MANDATORY: Each trigger and positioned element pair must share a unique anchor name. */
+ anchor-name: --my-trigger;
+}
+
+[popover].anchored-overlay {
+ position-anchor: --my-trigger;
+ /* MANDATORY: Use anchor() on inset properties rather than position-area when using the polyfill on elements needing position-try-fallbacks. */
+ inset: auto;
+ top: anchor(bottom);
+ left: anchor(left);
+ margin: 0;
+}
+```
+
+#### Option 2: Progressive enhancement with `@supports` (no polyfill)
+
+If you do not ship the polyfill, **DO NOT** set `inset: auto` or `margin: 0` unconditionally on a `[popover]` element that relies on `position-area` or `anchor()`. In browsers without anchor positioning, `inset: auto` overrides the user-agent centering (`inset: 0; margin: auto`) while `position-area` is ignored, leaving the popover stranded at `(0, 0)` or overlapping its trigger.
+
+Instead, gate `inset: auto` and `margin: 0` inside `@supports` for the specific positioning feature used (for example, `@supports (position-area: block-end)` or `@supports (top: anchor(bottom))`) so unsupported browsers retain the default centered popover placement, or provide a matching `@supports not (...)` fallback layout (such as a fixed bottom sheet):
+
+```css
+@supports (position-area: block-end) {
+ [popover].anchored-overlay {
+ inset: auto;
+ margin: 0;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
+ }
+}
+
+@supports not (position-area: block-end) {
+ /* Optional: override default popover centering with a fixed bottom bar */
+ [popover].anchored-overlay {
+ position: fixed;
+ inset: auto 0 0 0;
+ width: auto;
+ margin: 0;
+ }
+}
+```
+
+### Fallbacks & browser support for Cross-document view transitions
+
Browser support for Cross-document view transitions: Limited availability.
Supported by: Chrome 126 (Jun 2024), Edge 126 (Jun 2024), and Safari 18.2 (Dec 2024).
Unsupported in: Firefox.
+
+Cross-document view transitions are a progressive enhancement. In browsers that do not support `@view-transition { navigation: auto; }`, the rule (along with `blocking="render"` and `<link rel="expect">` on the destination page) degrades gracefully and clicking the link performs a standard page navigation without the morph animation.
diff --git a/skills/modern-web-guidance/guides/ui-components/menu.md b/skills/modern-web-guidance/guides/ui-components/menu.md
index 94809f5..0446716 100644
--- a/skills/modern-web-guidance/guides/ui-components/menu.md
+++ b/skills/modern-web-guidance/guides/ui-components/menu.md
@@ -1,26 +1,19 @@
-<!-- Baseline best practices to be referenced by any guide that involves a popup menu (dropdown menus, context menus, overflow menus, etc)
+# Build a popup menu
-Include:
-- fixed-size icon slot (no subgrid)
-- proper keyboard nav
-- safe triangles for submenus
-- converting to drawer on small screens?
--->
+This guide covers one popup menu: a list of commands or links that users move through with arrow keys. What opens it does not matter: a button (an "Actions" or overflow button), an item in another menu (a submenu), or no visible trigger at all (a context menu).
-# Build a dropdown menu
+Several triggers on one page are independent menus unless you build a bar: each is its own `Tab` stop, and nothing links them. A row of menus that act as one widget (File, Edit, View: one `Tab` stop, `ArrowLeft`/`ArrowRight` between them, hover switching) is an application menu bar. Build each menu as described here, then see `app-menus` (via `npx -y modern-web-guidance@latest retrieve "app-menus"`) for what links them.
-This guide covers any popup menu: dropdown, context, overflow, and the menu bars that open them. The worked example is an application command menu, where items change the interface (create, save, preferences).
-
-### Commands, links, and what makes a menu
+## Commands, links, and what makes a menu
Two independent choices. Everything else here applies to both.
-* **Element, per item.** A command is a `<button type="button">`; a destination is an `<a href>` that still opens in a new tab, copies as a URL, and works without script. A dropdown may mix them freely: two links and six commands, or one command and six links, changes nothing below.
-* **Interaction model, per dropdown.** Arrow keys, `Home`/`End`, and `Esc` make it a menu: add the focusgroup, let it infer `menuitem` on every item whether button or link, and make it look like one (a continuous bar or a trigger with a dropdown indicator; see "Menubar or separate menu buttons" below). A short list of links users `Tab` through is navigation: no focusgroup, no `role="menu"`, `role="menuitem"`, or `aria-haspopup="menu"`; keep the popover, `Esc`, and focus restoration, and see the navbar guide.
+* **Element, per item.** A command is a `<button type="button">`; a destination is an `<a href>` that still opens in a new tab, copies as a URL, and works without script. A menu may mix them freely: two links and six commands, or one command and six links, changes nothing below.
+* **Interaction model, per menu.** Arrow keys, `Home`/`End`, and `Esc` make it a menu: add the focusgroup, let it infer `menuitem` on every item whether button or link, and make it look like one (a trigger with a dropdown indicator, or a continuous bar for an application menu bar). A short list of links users `Tab` through is navigation: no focusgroup, no `role="menu"`, `role="menuitem"`, or `aria-haspopup="menu"`; keep the popover, `Esc`, and focus restoration. For navigation, see `navbar` (via `npx -y modern-web-guidance@latest retrieve "navbar"`).
Content never decides the roles. A "Products" dropdown of links can be a menu; an "Account" dropdown of commands cannot be navigation.
-Use the menu pattern only for a composite widget with one tab stop and arrow-key navigation. Use a `<div focusgroup="menu nomemory">`, not the HTML `<menu>` element. Do not add `role="menu"` or `role="menuitem"` in the shared markup: native focusgroup infers those roles, and explicit roles block that inference. Add them only in the unsupported-browser fallback below. `nomemory` makes reopening start at the first item. Focusgroup moves focus; script handles preview, activation, and focus restoration.
+Use the menu pattern only for a composite widget with one tab stop and arrow-key navigation. Use a `<div focusgroup="menu nomemory">`, not the HTML `<menu>` element. Do not add `role="menu"` or `role="menuitem"` in the shared markup: native focusgroup infers those roles, and explicit roles block that inference. Add them only in the unsupported-browser fallback below. `nomemory` makes reopening start at the first item. Focusgroup moves focus; script handles activation, submenu preview, and focus restoration.
## Open and position the menu
@@ -28,18 +21,20 @@ Make each trigger a command invoker with `commandfor` and `command="toggle-popov
Place each popover immediately after its trigger. Browsers add an implicit `aria-details` relationship only when the popover is not the next sibling, so this placement avoids it without extra attributes.
+A menu with no trigger button opens from script with `showPopover({ source })`. `source` sets the implicit anchor, so pass the element the menu belongs to: the right-clicked card, or the focused element when a keyboard shortcut opens it. To open at a point instead (the pointer position, or the caret for an `@`-mention picker), anchor positioning still needs an element, so use a placeholder: an empty, zero-size `position: fixed` element kept directly before the menu, moved to the point with `left` and `top` on each open, and passed as `source`. A zero-size anchor puts the menu's corner at the point, as a native context menu does, and the flip fallbacks below still apply. Name the menu with `aria-label` instead of `aria-labelledby`. Everything else in this guide applies unchanged; where it says "trigger" for positioning, read the placeholder.
+
```html
<!-- Command invoker: the browser toggles the popover on click, Enter, and Space -->
-<button id="file-trigger" class="trigger" type="button" aria-haspopup="menu" aria-expanded="false"
- commandfor="file-menu" command="toggle-popover">
- File
+<button id="actions-trigger" class="trigger" type="button" aria-haspopup="menu" aria-expanded="false"
+ commandfor="actions-menu" command="toggle-popover">
+ Actions
</button>
<!-- Immediately after its trigger, so browsers add no implicit aria-details -->
-<div id="file-menu" popover="auto">
+<div id="actions-menu" popover="auto">
<!-- Nested, not on the popover: Chromium otherwise drops focusgroup keyboard behavior -->
- <div focusgroup="menu nomemory" aria-labelledby="file-trigger">
- <button type="button">New file</button>
- <button type="button">Save</button>
+ <div focusgroup="menu nomemory" aria-labelledby="actions-trigger">
+ <button type="button">Duplicate</button>
+ <button type="button">Rename</button>
<button id="export-trigger" type="button" aria-haspopup="menu" aria-expanded="false"
commandfor="export-menu" command="toggle-popover">
Export <span aria-hidden="true">›</span>
@@ -55,30 +50,22 @@ Place each popover immediately after its trigger. Browsers add an implicit `aria
</div>
```
-Name each menu with `aria-labelledby` pointing at its trigger. Keep decorative submenu indicators in CSS, or add `aria-hidden="true"`. Give triggers with `aria-expanded="true"` a visible active style so users can tell which menu is open or previewed.
-
-### Menubar or separate menu buttons
-
-Pick one form for the top-level triggers. Role, keyboard model, and styling must match: visually separate buttons signal one `Tab` stop each.
-
-* **Menubar.** `role="menubar"` on the container (never on a popover), styled as one continuous bar with no gaps between triggers. One `Tab` stop; `ArrowLeft`/`ArrowRight` move between triggers; hover switches open menus. Use for an application command bar.
-* **Separate menu buttons.** Each trigger is its own `Tab` stop and looks like a standalone button. No `role="menubar"`, no arrow keys between triggers, no preview on focus, no hover switching. Wrap in `<nav>` if they navigate, otherwise no role. Use for toolbars and page headers.
-
-The rest of this guide describes the menubar form. For separate buttons, keep everything inside each menu and drop the menubar-level behavior.
+Name each menu with `aria-labelledby` pointing at its trigger. Keep decorative submenu indicators in CSS, or add `aria-hidden="true"`. Give triggers with `aria-expanded="true"` a visible active style so users can tell which menu is open. Outside a menu bar, style each trigger as a standalone button: it is its own `Tab` stop, and the styling must say so. Anything that links triggers (`role="menubar"`, arrow keys between them, preview on focus) belongs to the application menu bar.
### Position the menu with CSS Anchor Positioning
Use CSS anchor positioning, not JavaScript coordinates. Both `command="toggle-popover"` and `showPopover({ source: trigger })` set an implicit anchor, so do not add per-menu `anchor-name` or `position-anchor` rules. Menu behavior must not depend on anchor positioning.
```css
-/* Top-level menus sit below their trigger. The implicit anchor comes from the invoker or source. */
-[popover] {
+/* Top-level menus sit below their trigger, flipping when they would overflow. The implicit anchor comes from the invoker or source. */
+[popover]:has(> [focusgroup~="menu"]) {
position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
inset: auto;
}
-/* A popover nested in another popover is a submenu: beside its parent item, flipping when it would overflow. */
-[popover] [popover] {
+/* A popover directly inside a menu is a submenu: beside its parent item, flipping when it would overflow. */
+[focusgroup~="menu"] > [popover] {
position-area: inline-end span-block-end;
position-try-fallbacks: flip-inline, flip-block, --below;
}
@@ -105,49 +92,45 @@ Optional. Under 150 ms, `opacity` and a small `translate` only, same for submenu
```css
@media (prefers-reduced-motion: no-preference) {
/* Closing: this rule is in effect once :popover-open is removed. */
- [popover] {
+ [popover]:has(> [focusgroup~="menu"]) {
opacity: 0;
translate: 0 -.25rem;
- transition: opacity .15s, translate .15s, display .15s allow-discrete, overlay .15s allow-discrete;
+ transition: opacity, translate, display, overlay;
+ transition-duration: .15s;
+ /* Separate after transition so the shorthand doesn't reset it or fail in older browsers */
+ transition-behavior: allow-discrete;
}
/* Opening: faster. */
- [popover]:popover-open {
+ [popover]:has(> [focusgroup~="menu"]):popover-open {
opacity: 1;
translate: 0 0;
transition-duration: .1s;
@starting-style { opacity: 0; translate: 0 -.25rem; }
}
- /* Switching between open menubar menus is instant, as in native menubars. */
- [role="menubar"]:has(> [popover]:popover-open) > [popover] {
- transition: none;
- }
}
```
-`@starting-style` is not a repeat of `[popover]`: a closed popover is `display: none`, and transitions do not run from an unrendered state, so it supplies the before-values for the open. Without it the open snaps and only the close animates. `display` and `overlay` with `allow-discrete` keep the popover rendered and in the top layer until the close transition ends.
+`@starting-style` is not a repeat of `[popover]`: a closed popover is `display: none`, and transitions do not run from an unrendered state, so it supplies the before-values for the open. Without it the open snaps and only the close animates. `display` and `overlay` with `transition-behavior: allow-discrete` (set as a separate declaration after `transition` so older browsers do not ignore the entire `transition` declaration) keep the popover rendered and in the top layer until the close transition ends.
## Keyboard and focus
Do not add a second roving-tabindex system inside a focusgroup. Script covers only what the invokers and focusgroup do not:
-* **One tab stop for the menubar.** `Tab` enters at the first top-level trigger. `ArrowLeft` and `ArrowRight` move between top-level triggers and wrap at either end. `Home` and `End` on a trigger enter its menu at the first or last item.
- * **Note: which trigger `Tab` returns to.** The APG allows either the first trigger or the last one used. The guide specifies the first, but the demo moves the tab stop with `ArrowLeft` and `ArrowRight`, so after keyboard navigation `Shift`+`Tab` returns to the last trigger reached. Pointer use does not move it, so the same sequence can land on a different trigger. Either behavior is acceptable; pick one and keep it consistent.
-* **Preview.** Focusing a top-level trigger shows its menu and sets `aria-expanded="true"`. Focus stays on the trigger, and no item is focused. Blurring the trigger closes a preview-only menu.
-* **Enter and Space on a preview.** They close the preview and keep focus on the trigger. The native `toggle-popover` action handles this, so the script must not intercept these keys.
-* **ArrowDown on a preview.** Converts it to an open menu and focuses the first item.
-* **Pointer click on an open or previewed trigger.** Closes it natively; it does not enter the menu.
- * **Known difference on submenu triggers.** A pointer click on a submenu trigger also toggles natively, so it can close a submenu that hover already previewed, or open one that has not appeared yet. Native menus only open it and never close it. This is harmless, so the guide accepts it.
+* **The trigger is an ordinary button.** `Tab` reaches it like any other button, and focusing it does not open the menu. `Enter`, `Space`, and click toggle the menu natively, so the script must not intercept these keys.
+* **Keyboard open enters the menu.** Opening with `Enter` or `Space` focuses the first enabled item. `ArrowDown` on a trigger opens its menu if it is closed and focuses the first item either way, so arrow keys also work after a pointer open.
* **Pointer click on a closed trigger.** Opens it natively. Focus stays on the trigger; no item is focused. Only keyboard opens enter the menu.
+* **Pointer click on an open trigger.** Closes it natively; it does not enter the menu.
+ * **Known difference on submenu triggers.** A pointer click on a submenu trigger also toggles natively, so it can close a submenu that hover already previewed, or open one that has not appeared yet. Native menus only open it and never close it. This is harmless, so the guide accepts it.
* **Pointer over an item.** Focuses it without a ring, so hover and focus are one item.
-* **Pointer over another top-level trigger while a menu is open.** Closes it and previews the hovered one, focusing its trigger without a ring. Nothing open: hover does nothing.
-* **Pointer over a submenu trigger.** Previews its submenu after a short delay (pointer focus runs the same preview-on-focus). A sibling item closes it.
* **Within a menu.** `ArrowUp` and `ArrowDown` move between enabled items. `Home` and `End` move to the first and last enabled item, which the script handles.
-* **ArrowLeft or ArrowRight in an open top-level menu.** Closes it and previews the adjacent menu with focus on its trigger, wrapping at either end. `ArrowDown` then enters it. Left and Right never land inside a menu.
-* **ArrowRight on a submenu trigger.** Opens the submenu and focuses its first item.
-* **ArrowRight on a submenu item without a child submenu.** Closes the hierarchy and previews the next top-level menu while focus stays on its trigger. `ArrowDown` then enters it.
+* **Submenu preview.** Focusing a submenu trigger, by arrow key or by pointer (which focuses it after a short delay), shows its submenu and sets `aria-expanded="true"`. Focus stays on the trigger, and no submenu item is focused. Moving to a sibling item closes the preview.
+* **Enter or Space on a previewed submenu trigger.** They close the preview and keep focus on the trigger. The native `toggle-popover` action handles this.
+* **ArrowRight on a submenu trigger.** Opens the submenu if needed and focuses its first item.
* **ArrowLeft or Escape in a submenu.** Closes only that submenu and restores focus to its trigger. The parent menu stays open.
+* **Escape in a top-level menu.** Closes it and restores focus to its trigger.
* **Enter or Space on a command.** Activates it and closes all open menus.
* **Tab.** Leaves the menu system. Do not trap focus or step through every command. Closing must not leave focus inside hidden content.
+* **No trigger button.** A menu opened from script focuses its first item when it was opened from the keyboard, and on close restores focus to the element that had it before the menu opened.
The `command` event fires before `toggle-popover` opens the menu, so focus cannot move into the menu there. Move focus in the `toggle` event instead. HTML restores focus only for the first `popover="auto"` in a stack, so nested levels must restore focus to their trigger explicitly.
@@ -158,38 +141,41 @@ Implement the behaviors above for your own markup. Arrow, `Home`/`End`, wrap-aro
### Keyboard and focus handling
1. **One open path.** Opening by keyboard calls `trigger.click()`, so the invoker's `toggle-popover` is the only way a menu opens. Mark the menu so the `toggle` handler enters it, keyboard opens only. On a pointer open, `toggle` focuses the trigger without a ring instead, because `pointerdown` prevented focus and arrow keys must still work.
-2. **Preview on focus.** Focusing a trigger calls `showPopover({ source: trigger })` so the menu anchors to it. Ignore focus returning from inside the trigger's own menu, or from another window (flag on window `blur`, cleared a tick after window `focus`, or app-switching reopens the last menu). Hide a previewed menu on `blur` unless focus moved into it.
+2. **Submenu preview on focus.** Focusing a submenu trigger calls `showPopover({ source: trigger })` so the submenu anchors to it. Ignore focus returning from inside the trigger's own submenu (after `Escape`), or from another window (flag on window `blur`, cleared a tick after window `focus`). Hide a previewed submenu on `blur` unless focus moved into it. Top-level triggers get no preview: focusing them does nothing.
3. **Move focus in `toggle`, not `command`.** `command` fires before the menu opens.
4. **Restore focus to the trigger yourself.** Focus the trigger before `hidePopover()`. After a pointer activation, restore focus without a ring (`focus({ focusVisible: false })`), or the trigger shows the keyboard focus outline after a mouse click; keyboard activations keep the ring. A click with `event.detail === 0` came from the keyboard.
5. **Close one level at a time.** Call `stopPropagation()` on `Escape` and `ArrowLeft` in a submenu, or the parent's listener closes it too.
### Pointer handling
-1. **Pointer click toggles.** Call `preventDefault()` on `pointerdown` so the click doesn't move focus and start a preview mid-click. Remember which trigger was pressed. Clicking a closed or previewed trigger opens or closes it natively and never enters the menu; only keyboard opens enter it. Do not intercept the click.
-2. **Hover follows focus.** Style `:hover` and `:focus-visible` separately. On `pointermove` over an item, call `focus({ focusVisible: false })`; browsers that ignore the option paint no ring for pointer focus anyway.
-3. **Hover switches open menus.** On `pointerenter` of a top-level trigger while another top-level menu is open: hide it, focus the hovered trigger without a ring, and preview on focus (see above) previews it. Nothing open: do nothing.
-4. **Safe triangle.** A fixed CSS bridge is too narrow: it only works when the pointer starts near the parent's edge. Let CSS draw the bridge and use script only to report the pointer:
+1. **Pointer click toggles.** Call `preventDefault()` on `pointerdown` so the click doesn't move focus. Remember which trigger was pressed. Clicking a closed trigger opens it natively and never enters the menu; only keyboard opens enter it. Do not intercept the click.
+2. **Hover follows focus.** Style `:hover` and `:focus-visible` separately. On `pointermove` over an item, call `focus({ focusVisible: false })`; browsers that ignore the option paint no ring for pointer focus anyway. Pointer focus on a submenu trigger runs the same submenu preview as keyboard focus, after a short delay so a pointer crossing the item does not flash its submenu.
+3. **Safe triangle.** A static CSS bridge is too narrow: it only works when the pointer starts near the parent's edge. Let CSS draw a triangle from where the pointer left the trigger, and use script only to place it:
* Run this only when `matchMedia('(hover: hover)').matches`; it is irrelevant to touch and keyboard.
- * Start when the pointer leaves a submenu trigger whose submenu is open. Skip a `--below` submenu, which has no side edge.
- * Set `--bridge-x` and `--bridge-y` (the pointer, in px relative to the submenu), `--bridge-edge` (the submenu's near-edge x: `0` when the pointer is to its left, its width when it flipped) and `--bridge-height` on the submenu, and `data-bridge` to switch the bridge on.
- * Stop after about 300 ms, when the pointer reaches an item in the submenu, or when the submenu closes. Remove the listener and the attribute. Nothing runs after that.
- * CSS gives the submenu a `::before` clipped to a triangle from the pointer to the near-edge corners. It sits over the sibling items on the pointer's path, so they never receive the hover that would close the submenu. `clip-path` also limits hit testing, so the rest of the parent menu stays interactive.
- * The submenu needs `overflow: visible` (a popover clips by default), and the pseudo-element extends past it, so offset the shape's points by that extent.
+ * Start on `pointerleave` of a submenu trigger whose submenu is open, at the event's position. Skip a `--below` submenu, which has no side edge.
+ * Set `--pointer-x` and `--pointer-y` (the pointer, in px relative to the submenu's box) on the submenu, and `data-bridge` to switch the bridge on. CSS derives the rest: which side the pointer is on from the sign of `--pointer-x`, and the submenu's near-edge corners from percentages of the pseudo-element's own box.
+ * Pointer moves over the bridge target the submenu, so listen there: keep the bridge while the pointer moves toward the submenu, and remove the attribute about 300 ms after it rests, when it moves away from the submenu horizontally, when it reaches an item in the submenu, or when the submenu closes. A fixed 300 ms from the leave is too short for an unhurried diagonal; a bridge that ignores a reversal makes a change of mind wait.
+ * CSS gives the submenu a `::before` clipped to a triangle from that point to the near-edge corners, with a few px of slack around the point (`--bridge-slack` below) so the pointer's own position is inside the shape rather than on its edge. The apex does not follow the pointer: an apex at the pointer turns every move into a direction test, and the first step off a straight line closes the submenu. It sits over the sibling items on the pointer's path, so they never receive the hover that would close the submenu. `clip-path` also limits hit testing, so the rest of the parent menu stays interactive.
+ * The submenu needs `overflow: visible` (a popover clips by default). The pseudo-element extends `100vw`/`100vh` past it on every side, so the shape's points are offset by that, and `100%` of its box is the submenu plus twice that.
* Follow-up: a curved path (`shape()` curve commands) follows real pointer arcs better than a straight triangle.
```css
-[popover] [popover] {
+[focusgroup~="menu"] > [popover] {
overflow: visible;
&[data-bridge]::before {
content: "";
position: absolute;
- inset: -100vh -100vw; /* Room for the triangle, which can extend far outside the submenu. */
- clip-path: shape(
- from calc(100vw + var(--bridge-x)) calc(100vh + var(--bridge-y)),
- line to calc(100vw + var(--bridge-edge)) 100vh,
- line to calc(100vw + var(--bridge-edge)) calc(100vh + var(--bridge-height)),
- close
+ inset: -100vh -100vw; /* Room for the triangle. In this box the submenu runs from 100vw/100vh to 100% - 100vw/100vh. */
+ --bridge-slack: 5px; /* The apex moves away from the submenu by this much and is twice this tall. */
+ --bridge-side: sign(var(--pointer-x)); /* -1: pointer left of the submenu, 1: right. */
+ --bridge-edge: calc(50% + var(--bridge-side) * (50% - 100vw)); /* The submenu's near edge. */
+ --bridge-apex: calc(100vw + var(--pointer-x) + var(--bridge-side) * var(--bridge-slack));
+ clip-path: polygon(
+ var(--bridge-apex) calc(100vh + var(--pointer-y) - var(--bridge-slack)),
+ var(--bridge-edge) 100vh,
+ var(--bridge-edge) calc(100% - 100vh),
+ var(--bridge-apex) calc(100vh + var(--pointer-y) + var(--bridge-slack))
);
}
}
@@ -198,40 +184,42 @@ Implement the behaviors above for your own markup. Arrow, `Home`/`End`, wrap-aro
```js
const canHover = matchMedia('(hover: hover)');
-// Call on pointerleave of a submenu trigger, with that trigger's submenu.
+// Call on pointerleave of a submenu trigger, with its submenu.
function startBridge(submenu, event) {
if (!canHover.matches || !submenu.matches(':popover-open')) return;
const rect = submenu.getBoundingClientRect();
- if (event.clientX >= rect.left && event.clientX <= rect.right) return; // --below: no side edge.
- const style = submenu.style;
- style.setProperty('--bridge-edge', `${event.clientX < rect.left ? 0 : rect.width}px`);
- style.setProperty('--bridge-height', `${rect.height}px`);
- const update = ({ clientX, clientY, target }) => {
- if (target !== submenu && submenu.contains(target)) return stop(); // Reached an item.
- style.setProperty('--bridge-x', `${clientX - rect.left}px`);
- style.setProperty('--bridge-y', `${clientY - rect.top}px`);
- };
- const timer = setTimeout(() => stop(), 300);
+ const left = event.clientX < rect.left;
+ if (!left && event.clientX <= rect.right) return; // --below: no side edge.
+ submenu.style.setProperty('--pointer-x', `${event.clientX - rect.left}px`);
+ submenu.style.setProperty('--pointer-y', `${event.clientY - rect.top}px`);
+ submenu.dataset.bridge = '';
+ let timer;
+ let lastX = event.clientX;
const stop = () => {
clearTimeout(timer);
- document.removeEventListener('pointermove', update);
- submenu.removeEventListener('toggle', stop);
+ submenu.removeEventListener('pointermove', extend);
submenu.removeAttribute('data-bridge');
};
- update(event);
- submenu.dataset.bridge = '';
- document.addEventListener('pointermove', update);
+ const extend = ({ target, clientX }) => {
+ // Reached an item, or turned away from the submenu.
+ if (target !== submenu || (left ? clientX < lastX : clientX > lastX)) return stop();
+ lastX = clientX;
+ clearTimeout(timer);
+ timer = setTimeout(stop, 300);
+ };
+ timer = setTimeout(stop, 300);
+ submenu.addEventListener('pointermove', extend);
submenu.addEventListener('toggle', stop, { once: true });
}
```
-Hover follows focus (item 2) stays a plain `pointermove` handler: it needs no triangle logic.
+Hover follows focus (item 2) needs one guard. The move that leaves the trigger was hit-tested before the bridge existed, so its target is the sibling under the pointer. Skip the focus when `document.elementFromPoint(event.clientX, event.clientY)` is not inside the item; later moves on the path hit the bridge, whose target is the submenu, not an item.
Also:
* **Outside focus.** Close every open menu when focus lands outside the menu system (a `document` `focusin` listener).
* **Command activation.** Announce it, then hide the root menu and restore focus to its trigger, without a ring if the activation came from a pointer. For checkable items (`menuitemcheckbox`, `menuitemradio`), wait about 300 ms before closing so the changed check mark is visible. Style a closed trigger as active only on `:focus-visible`; otherwise the restored (ringless) focus leaves it highlighted after a pointer selection.
-* **`aria-expanded`.** Set it only in the `toggle` listener. It covers preview and open states, and the trigger's `aria-expanded` stays `"true"` while its menu is previewed or open.
+* **`aria-expanded`.** Set it only in the `toggle` listener. It covers preview and open states, and a trigger's `aria-expanded` stays `"true"` while its menu is previewed or open.
* **Helpers.** The fallbacks below assume helpers you define for your markup: `triggers` (all `[commandfor]` buttons), `menuFor(trigger)`, `isOpen(menu)`, `closeAndRestore(menu, { fromPointer })` (focus the trigger, without a ring when `fromPointer`, then `menu.hidePopover()`), `enterOnOpen` (a `WeakSet` of menus to enter once open) and `pointerTrigger` (the trigger last pressed by a pointer).
### Submenus
@@ -260,8 +248,8 @@ Also:
An instruction cannot guarantee behavior, so test the result. Open the page and check each of these with the real keyboard and mouse; fix and re-test any that fail:
-* **Keyboard.** `Tab` lands on the first trigger once; `ArrowDown` enters; `Escape` closes one level and returns focus to its trigger; `Tab` closes every menu.
-* **Pointer open.** Clicking a trigger opens its menu with focus on the trigger and no ring; clicking again closes it.
+* **Keyboard.** `Tab` lands on a trigger without opening its menu; `ArrowDown` opens and enters; `Escape` closes one level and returns focus to its trigger; `Tab` closes every menu.
+* **Pointer open.** Clicking a trigger opens its menu with focus on the trigger and no ring; `ArrowDown` then enters; clicking again closes it.
* **Pointer command.** Clicking a command closes every menu and shows no focus ring on the trigger.
* **Submenu.** Moving diagonally from the middle of a submenu trigger to a submenu item keeps it open; moving to an unrelated sibling closes it.
* **Narrow screen.** At 375 px no submenu covers its own trigger.
@@ -306,13 +294,15 @@ When a row has an icon, label, and shortcut or submenu indicator, reserve a fixe
Put a trailing indicator or shortcut in a `<span class="hint" aria-hidden="true">` inside the button; the submenu trigger already announces its popup.
-## Progressive enhancement and fallbacks
+## Fallback strategies
### Fallbacks & browser support for focusgroup
-focusgroup is not natively supported by any major browser yet.
+Browser support for focusgroup: Limited availability.
+Supported by: Chrome 150 (Jun 2026) and Edge 150 (Jul 2026).
+Unsupported in: Firefox and Safari.
-Keep `focusgroup="menu nomemory"` in the markup. If `'focusGroup' in HTMLElement.prototype` is false, install Up, Down, Home, and End, set `role="menu"` on each menu container, and `role="menuitem"` on buttons with no role; leave checkable items, `<hr>`, and `role="group"` alone. Never install it when native focusgroup is present. Left, Right, preview, open, and close are author script either way.
+Keep `focusgroup="menu nomemory"` in the markup. If `'focusGroup' in HTMLElement.prototype` is false, install Up, Down, Home, and End, set `role="menu"` on each menu container, and `role="menuitem"` on buttons with no role; leave checkable items, `<hr>`, and `role="group"` alone. Never install it when native focusgroup is present. Submenu preview, open, and close are author script either way.
```js
if (!('focusGroup' in HTMLElement.prototype)) {
@@ -352,22 +342,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
-
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -375,8 +359,6 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
-
### Fallbacks & browser support for Anchor positioning
Browser support for Anchor positioning: Limited availability.
@@ -408,3 +390,26 @@ Without invokers, `command="toggle-popover"` does nothing, so script must toggle
* If the menu is open, close it with `closeAndRestore(menu)`. Otherwise call `menu.showPopover({ source: trigger })`.
* Mark the menu in `enterOnOpen` unless the click came from the pressed trigger (`pointerTrigger`), so only keyboard opens enter the menu.
* `Enter` and `Space` still work because they generate a click on buttons.
+
+### Fallbacks & browser support for `:has()`
+
+Baseline status for :has(): Widely available. It's been Baseline since 2023-12-19.
+Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 121 (Dec 2023), and Safari 15.4 (Mar 2022).
+
+If targeting browsers without `:has()`, add a class to each menu popover instead of selecting `[popover]:has(> [focusgroup~="menu"])`.
+
+### Fallbacks & browser support for `sign()`
+
+Baseline status for abs() and sign(): Newly available. It's been Baseline since 2025-06-26.
+Supported by: Chrome 138 (Jun 2025), Edge 138 (Jun 2025), Firefox 118 (Sep 2023), and Safari 15.4 (Mar 2022).
+
+If your Baseline target lacks `sign()`, skip `--bridge-side` and pick the edge and the apex nudge with `clamp()`: a large multiplier pushes `--pointer-x` past either bound, so the result is one end or the other.
+
+```css
+@supports not (width: calc(sign(1px) * 1px)) {
+ [data-bridge]::before {
+ --bridge-edge: clamp(100vw, 50% + var(--pointer-x) * 1e6, 100% - 100vw);
+ --bridge-apex: calc(100vw + var(--pointer-x) + clamp(-1 * var(--bridge-slack), var(--pointer-x) * 1e6, var(--bridge-slack)));
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-components/navbar.md b/skills/modern-web-guidance/guides/ui-components/navbar.md
new file mode 100644
index 0000000..ff15679
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/navbar.md
@@ -0,0 +1,281 @@
+# Responsive Site Navigation
+
+Build a site navigation bar that uses one semantic navigation tree at every size, presents a native popover when the links do not fit, becomes an inline navigation when they do, and identifies the current page.
+
+This guide describes site-navigation integration. It is navigation, not an application menu: links stay in the `Tab` order, with no `focusgroup`, `role="menubar"`, `role="menu"`, `role="menuitem"`, `aria-haspopup="menu"`, or arrow-key handling. For application command menus, see `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`); for menubars, see `app-menus` (via `npx -y modern-web-guidance@latest retrieve "app-menus"`). For the menu and chevron icons, see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`).
+
+For component-driven layouts, fluid sizing, and typographic line-wrapping, see `size-aware-styling` (via `npx -y modern-web-guidance@latest retrieve "size-aware-styling"`), `fluid-scaling` (via `npx -y modern-web-guidance@latest retrieve "fluid-scaling"`), and `improve-text-layout-and-legibility` (via `npx -y modern-web-guidance@latest retrieve "improve-text-layout-and-legibility"`).
+
+
+## Core Markup
+
+Use one `<nav>` landmark for narrow and wide layouts. Wrap it in a semantic `<header>` whose `is-wide` class selects the inline layout. The collapsed layout is the default, so it is also what you get without script.
+
+```html
+<header class="site-header">
+ <div class="header-inner">
+ <a class="site-logo" href="index.html">Acme</a>
+
+ <nav class="site-nav" aria-label="Primary">
+ <button
+ class="menu-button"
+ type="button"
+ popovertarget="site-menu"
+ popovertargetaction="toggle"
+ aria-controls="site-menu"
+ >
+ <!-- Decorative menu icon: insert as described in the icons guide -->
+ <span>Menu</span>
+ </button>
+
+ <ul id="site-menu" class="site-menu" popover="auto">
+ <li><a href="index.html" aria-current="page">Home</a></li>
+ <li><a href="about.html">About</a></li>
+ <li class="nav-dropdown">
+ <button
+ class="dropdown-trigger"
+ type="button"
+ aria-expanded="false"
+ aria-controls="services-menu"
+ popovertarget="services-menu"
+ >
+ Services
+ </button>
+ <ul id="services-menu" class="dropdown-list">
+ <li><a href="design.html">Design</a></li>
+ <li><a href="development.html">Development</a></li>
+ </ul>
+ </li>
+ </ul>
+ </nav>
+ </div>
+</header>
+```
+
+The button declaratively controls the menu with `popovertarget` and `aria-controls`. The `nav` remains the navigation landmark while the menu is closed. The trigger icon is decorative and the visible "Menu" text is the accessible name, so hide the icon from assistive technologies. For how to insert and hide icons, see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`). For the general popover control contract, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`). Unlike the menu guide, use `popovertarget`: one toggle needs no invoker commands. As in the menu guide, place each popover (the menu list, and the submenu list) immediately after its trigger so browsers add no implicit `aria-details`.
+
+
+## Narrow Layout: Popover Navigation
+
+When collapsed, keep `popover="auto"` on the navigation list. Anchor the fixed popover to the menu button and constrain its height so a long navigation can scroll without exceeding the viewport.
+
+There is no hard-coded breakpoint. Script collapses the navigation only when the inline row (brand, actions and every link) does not fit, so adding a link, a translation or larger text moves the point automatically. It adds `is-wide` to the header when the row fits; without script the header keeps the collapsed layout at every width.
+
+```css
+/* Keep the row's natural width measurable */
+.header-inner > * {
+ flex-shrink: 0;
+ white-space: nowrap;
+}
+
+.site-header {
+ .menu-button {
+ anchor-name: --menu-button;
+ }
+
+ .site-menu {
+ position: fixed;
+ inset: auto;
+ inset-block-start: anchor(--menu-button bottom);
+ inset-inline-end: 1rem;
+ inline-size: min(80dvw, 24rem);
+ max-inline-size: calc(100dvw - 2rem);
+ block-size: fit-content;
+ max-block-size: calc(100dvh - 6rem);
+ margin-block-start: 0.5rem;
+ overflow: auto;
+ }
+}
+```
+
+The `anchor()` declaration places the menu below the button; see Fallbacks for browsers without Anchor Positioning. For collision-aware positioning near viewport edges, see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`).
+
+
+## Wide Layout: Inline Navigation
+
+When the row fits, hide the collapsed-layout trigger and reset the popover presentation so the same list participates in the header as an inline navigation.
+
+```css
+.site-header.is-wide {
+ .menu-button {
+ display: none;
+ }
+
+ .site-menu {
+ position: static;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ inline-size: auto;
+ max-inline-size: none;
+ block-size: auto;
+ max-block-size: none;
+ overflow: visible;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ box-shadow: none;
+ }
+
+ .site-menu::backdrop {
+ display: none;
+ }
+}
+```
+
+CSS changes the presentation, but JavaScript decides which layout applies and must also synchronize the `popover` attribute with it. Measure the inline row: show it inline, compare `scrollWidth` with `clientWidth` on the header's inner row, then toggle `is-wide`. Add a temporary `is-measuring` class that sets `transition: none` on descendants for the measurement and remove it in `requestAnimationFrame`, otherwise the menu animates from its inline styles on every resize and flickers. Keep the navigation as a popover only in the collapsed layout; remove the attribute in the inline layout. Removing it closes an open popover, so note whether the menu was open and call `showPopover()` again if the layout is still collapsed; otherwise a resize closes the open menu. Run one shared function from `ResizeObserver`s on the header and the navigation list, so font loading and text changes are caught without special cases. Remeasure while inline on every notification, but while collapsed only when the header's width has grown. Switching to inline just to measure on every shrink makes the layout thrash. The tradeoff is that a collapsed menu that gets smaller by itself (for example a shorter translation) stays collapsed until the header grows. Do not infer the layout from a hidden trigger.
+
+
+## Nested Site Navigation
+
+Use a `<button>` with `aria-expanded` and `aria-controls` as the trigger for nested site navigation, followed immediately by the submenu list. DO NOT use `<details>` and `<summary>`: `<summary>` should map to a `button` role, but has not been consistently implemented in browsers, so screen readers announce it inconsistently (for example as "summary" or "disclosure triangle").
+
+One list must be an inline disclosure when narrow and a floating popover when wide. A top-layer popover cannot render in flow, so `popover` is set only in the wide layout, where `popovertarget` opens it natively. Leave `popover` off the submenu in the markup: without script it stays a nested list inside the menu, matching the narrow layout. In the narrow layout a small click handler toggles `hidden` and `aria-expanded`. Hide the narrow submenu from script, not in the markup.
+
+Synchronize the layout state from the same function that handles the navigation list. When inline, set `popover="auto"` on the submenu, clear `hidden`, and let the native `toggle` event drive `aria-expanded`. When narrow, remove `popover`, set `hidden` from script, and let a click handler toggle `hidden` and `aria-expanded`:
+
+```js
+const wide = inner.scrollWidth <= inner.clientWidth; // measured with is-wide set
+if (wide) submenu.setAttribute("popover", "auto");
+else submenu.removeAttribute("popover");
+submenu.hidden = !wide;
+trigger.setAttribute("aria-expanded", "false");
+```
+
+> [!NOTE]
+> Use `setAttribute()`/`removeAttribute()`, NOT the `popover` JS property, as it can cause race conditions if popover is used through a polyfill.
+
+Do not add document-level click-outside, Escape or focus-restoration handlers. The native popover provides those interactions in the wide layout, and the narrow disclosure needs only the click handler. The declarative `popovertarget` makes the button the submenu's implicit anchor, so wide-layout positioning can use `position-area` without a separate `anchor-name` or `position-anchor` declaration.
+
+### Hover preview
+
+In the wide layout, open the submenu (`submenu.showPopover({ source: trigger })`) on `pointerenter` of the parent `<li>` when `matchMedia("(hover: hover)").matches` and `event.pointerType !== "touch"`, and hide it on `pointerleave` if it is still only hover-previewed (if the user clicks the trigger while previewing, clear the preview flag and call `event.preventDefault()` so the click pins it open instead of toggling it closed). Do not open it when the trigger receives keyboard focus; only `Enter` or `Space` toggles it. Close the open submenu when focus moves to an element outside the submenu's whole list item (`focusout` with a non-null `relatedTarget` outside it), so tabbing or `Shift`+`Tab`bing away closes it.
+
+Position the wide submenu below its trigger with CSS Anchor Positioning (`position-area: block-end span-inline-end` and `position-try-fallbacks: flip-block, flip-inline`). For collision-aware positioning of a plain popover, see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`). Add a `::before` bridge across any margin gap above the submenu (with `overflow: visible` on the popover) so moving the pointer from the trigger into the submenu does not fire `pointerleave`, and set `height: auto` to prevent Safari from stretching the positioned popover to its placement area:
+
+```css
+.site-header.is-wide {
+ .dropdown-list[popover] {
+ position: absolute;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline;
+ inset: auto;
+ height: auto;
+ inline-size: max-content;
+ min-inline-size: 12rem;
+ margin-block-start: 0.5rem;
+ overflow: visible;
+ }
+
+ .dropdown-list::before {
+ content: "";
+ position: absolute;
+ inset-inline: 0;
+ inset-block-end: 100%;
+ block-size: 0.5rem;
+ }
+
+ /* Also hides the list before script sets popover, so an open narrow disclosure cannot widen the measured row */
+ .dropdown-list:not(:is(:popover-open, .\:popover-open)) {
+ display: none;
+ }
+
+ .dropdown-list:is(:popover-open, .\:popover-open) {
+ display: grid;
+ }
+}
+```
+
+
+## Indicating the Current Page
+
+Use `aria-current="page"` to identify the current page. Set it at build time or with JavaScript, and use `[aria-current="page"]` as the CSS styling hook. The visual treatment is a design decision; do not assume a particular pseudo-element, border, or orientation. Do not indicate the current page with color alone (WCAG 1.4.1). Ensure the color of the visual indicator has a contrast of at least `3:1` with the background color.
+
+## Transitions and Accessibility
+
+If the navigation is animated (optional; add it when the abrupt open and close feels out of place), use `@starting-style`, include `display` and `overlay` in `transition`, and declare `transition-behavior: allow-discrete` as a separate property after `transition` (DO NOT put `allow-discrete` in the `transition` shorthand, which makes older browsers ignore the entire `transition` declaration) for both the mobile menu and the wide floating submenu. Animate only `opacity` and `translate`, and respect `prefers-reduced-motion`. For the reusable transition pattern, see `animate-element-entry-exit` (via `npx -y modern-web-guidance@latest retrieve "animate-element-entry-exit"`).
+
+### Optional: Narrow submenu slide-down
+
+Optional. In the narrow layout the submenu is an inline list toggled with `hidden`, which opens instantly by default and is fully functional that way. To slide it open and closed:
+
+- Keep the `[hidden]` list rendered with `display: grid` and `block-size: 0`, then transition `block-size` to `auto` with `interpolate-size: allow-keywords` and `clip-path: inset(-6px)` to clip the slide without cutting off the focus ring (not `overflow: clip`, which clips the ring; `6px` is an example, use at least the ring's outline width plus offset).
+- Set `content-visibility: hidden` on the `[hidden]` list, include `content-visibility` in `transition`, and declare `transition-behavior: allow-discrete` separately after `transition` so the content stays rendered until the close finishes.
+- Scope it to the collapsed layout and `prefers-reduced-motion: no-preference`; outside it, `[hidden]` must stay `display: none`. In the wide layout the submenu is a popover and must not be clipped.
+- For the general technique, see `animate-to-intrinsic-sizes` (via `npx -y modern-web-guidance@latest retrieve "animate-to-intrinsic-sizes"`).
+
+Use logical properties for sizing, spacing, and positioning. Use `dvw` and `dvh` for viewport-relative limits, provide visible `:focus-visible` indicators, and adapt custom borders and current-page indicators under `forced-colors: active`.
+
+
+## Fallbacks
+
+### Fallbacks & browser support for Popover
+
+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
+Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
+
+The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
+
+**Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
+ import("@oddbird/popover-polyfill");
+}
+```
+
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Fallbacks & browser support for Anchor positioning
+
+Browser support for Anchor positioning: Limited availability.
+Supported by: Safari 27 (Sep 2026).
+Unsupported in: Chrome, Edge, and Firefox.
+
+For the mobile menu, put an absolute fallback declaration before the `anchor()` declaration. Do not wrap this simple fallback in an `@supports` rule: an unsupported `anchor()` declaration is discarded while the preceding declaration remains valid. Without Anchor Positioning the menu still opens as a popover at a fixed offset from the top of the viewport.
+
+```css
+.site-header {
+ .site-menu {
+ /* Example-only offset: use roughly your header height. Browsers without anchor() keep this one. */
+ inset-block-start: 4.75rem;
+ inset-block-start: anchor(--menu-button bottom);
+ }
+}
+```
+
+For the wide floating submenu, without CSS Anchor Positioning a popover falls back to centered viewport placement, which detaches the submenu from its navbar trigger. Override the submenu to `position: fixed; margin: 0` inside `@supports not (position-area: block-end)`, and when `event.newState === "open" && !CSS.supports("position-area", "block-end")` in the submenu's `toggle` handler, compute `top` and `left` from `trigger.getBoundingClientRect()` and `submenu.getBoundingClientRect()` (placing it below the trigger, flipping above if `top + size.height > innerHeight`, and clamping `left` to `[0, innerWidth - size.width]`).
+
+### Transitions
+
+Baseline status for @starting-style: Newly available. It's been Baseline since 2024-08-06.
+Supported by: Chrome 117 (Sep 2023), Edge 117 (Sep 2023), Firefox 129 (Aug 2024), and Safari 17.5 (May 2024).
+
+Baseline status for transition-behavior: Newly available. It's been Baseline since 2024-08-06.
+Supported by: Chrome 117 (Sep 2023), Edge 117 (Sep 2023), Firefox 129 (Aug 2024), and Safari 17.4 (Mar 2024).
+
+Browser support for interpolate-size: Limited availability.
+Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
+Unsupported in: Firefox and Safari.
+
+Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.
+Supported by: Chrome 108 (Nov 2022), Edge 108 (Dec 2022), Firefox 130 (Sep 2024), and Safari 26 (Sep 2025).
+
+Gate the optional narrow submenu slide-down rules that override `[hidden]` with `display: grid` behind `@supports (interpolate-size: allow-keywords)`. Without the gate, browsers lacking keyword interpolation snap the list closed instead of sliding; with it, they keep native `[hidden]` behavior. Without `@starting-style` or `transition-behavior: allow-discrete`, the optional popover entry or exit transitions fall back to opening or closing immediately.
+
+Without script nothing adds `is-wide`, so the header stays collapsed: the menu button opens the native popover and the submenu is a nested list. Do not write a separate no-script layout or a `no-js` class.
+
diff --git a/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md b/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md
index 54f2d9d..6c5a6ab 100644
--- a/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md
+++ b/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md
@@ -2,31 +2,41 @@
## Overview
-A navigation drawer is a panel that slides in from the edge of the viewport over the page content, dimming everything behind it. It is opened from a trigger button and dismissed by swiping the panel off-screen, tapping the dimmed backdrop, or pressing Escape.
+A navigation drawer is a panel that slides in from the edge of the viewport over the page content, dimming everything behind it. It is opened from a trigger button and dismissed by swiping the panel off-screen, tapping the dimmed backdrop, activating an explicit Close button inside the panel, or pressing Escape.
This guide implements the drawer as:
-- A `popover="manual"` element promoted to the top layer so the panel and its `::backdrop` overlay every other element on the page, regardless of stacking context.
+- A top-layer element (a modal `<dialog>` or a `popover="manual"` element, see [Choose the drawer element](#choose-the-drawer-element)), so the panel and its `::backdrop` overlay every other element on the page, regardless of stacking context.
- A horizontally scrolling container with two CSS scroll-snap stops — one for "open", one for "closed" — so the swipe gesture is handled natively by the browser. This delivers momentum, velocity, and interruption tracking for free, with no JavaScript pointer-event code.
- A scroll-driven animation that ties the backdrop's opacity to the scroll position, so the dim fades in and out smoothly as the user drags the panel.
-- An `IntersectionObserver` on the panel that detects when it has fully entered or fully left the viewport, and uses those moments to update focus, `aria-expanded`, and `inert`.
+- An `IntersectionObserver` on the panel that detects when it has fully entered or fully left the viewport, and uses those moments to close the drawer and update its state.
This approach is preferred over JavaScript-driven `transform` animations because the scroll mechanism gives the user direct control of the panel's position (their finger drives it, not a tween) and it much more closely matches the interaction patterns that users are accustomed to in native mobile apps.
-## Implementation
+### Choose the drawer element
+
+First, decide whether the drawer is only ever a drawer, or whether the same element also becomes a regular, always-visible sidebar under certain conditions (e.g. on wide screens). If the request does not say, assume it is only ever a drawer.
+
+- **Only ever a drawer**: use a `<dialog>` element opened with `showModal()`. The browser makes the rest of the page inert, exposes the drawer as a modal dialog to assistive technologies, handles Escape, and restores focus on close. See [Implementation with `<dialog>`](#implementation-with-dialog).
+- **Also a sidebar**: use a regular element with `role="dialog"` and `popover="manual"`, and remove the `role` while it acts as a sidebar. A `<dialog>` element does not work here, since it is always exposed as a dialog, but a sidebar is not one. Because a popover is not modal, the code must handle modality manually. See [Implementation for a drawer that also acts as a sidebar](#implementation-for-a-drawer-that-also-acts-as-a-sidebar).
+
+## Implementation with `<dialog>`
### 1. Markup
-The drawer is a single popover containing a horizontal scroller, which contains the visible "sheet". The trigger button lives in the page content.
+The drawer is a single `<dialog>` containing a horizontal scroller, which contains the visible "sheet". The trigger button lives in the page content. The drawer's close button has an `autofocus` attribute so that this control receives focus when the drawer is opened.
```html
-<!-- popover="manual" is REQUIRED. Do not use popover="auto" or "hint". -->
-<div class="Drawer" id="drawer" popover="manual">
+<!-- MANDATORY: Provide an accessible name for the dialog with aria-label or,
+ if there is already text within the drawer that can act as its accessible name,
+ with aria-labelledby. -->
+<dialog class="Drawer" id="drawer" aria-label="Navigation drawer">
<div class="Drawer-scroller">
- <nav class="Drawer-sheet" tabindex="-1">
- <!-- tabindex="-1" makes the sheet programmatically focusable so we
- can move focus into it when the drawer opens, without adding it
- to the natural tab order. -->
+ <nav class="Drawer-sheet">
+ <!-- Close button that can be used to dismiss the drawer -->
+ <button id="drawer-close" aria-label="Close menu" autofocus>
+ <!-- close icon or blank if icon inserted via CSS -->
+ </button>
<ul>
<li><a href="/page-1">Page 1</a></li>
<li><a href="/page-2">Page 2</a></li>
@@ -34,7 +44,7 @@ The drawer is a single popover containing a horizontal scroller, which contains
</ul>
</nav>
</div>
-</div>
+</dialog>
<main>
<header>
@@ -44,41 +54,47 @@ The drawer is a single popover containing a horizontal scroller, which contains
aria-label="Menu"
aria-expanded="false"
aria-controls="drawer">
- <!-- MANDATORY: Inline decorative SVGs MUST define aria-hidden="true" -->
- <svg aria-hidden="true" viewBox="0 0 24 24">...</svg>
+ <!-- open icon or blank if icon inserted via CSS -->
</button>
</header>
<!-- Page content. -->
</main>
```
+See `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`) for maintaining accessibility when using icons.
+
### 2. Styles
-#### Reset the popover and fill the viewport
+#### Reset the dialog and fill the viewport
-The popover must cover the whole viewport so its `::backdrop` dims the entire page and the swipe surface extends edge-to-edge. The default user-agent popover styles (centered, auto-sized, bordered) get in the way and must be reset.
+The dialog must cover the whole viewport so that the swipe surface extends edge-to-edge. The default user-agent dialog styles (centered, size-capped, padded, bordered) get in the way and must be reset.
```css
.Drawer {
/* min() caps the sheet width on large screens but on a phone leaves
a 20% peek of page content visible, which is the affordance that
tells the user they can tap outside to dismiss. */
- --drawer-width: min(20em, 80dvw);
+ --drawer-width: min(20em, 80dvw, 100dvw - 24px);
/* Custom property driven by the scroll-driven animation below.
0 = drawer fully closed (transparent backdrop).
1 = drawer fully open (visible backdrop). */
--drawer-backdrop: 0;
- /* Reset UA popover style that would constrain the element. */
+ /* Reset UA dialog styles that would constrain the element. */
+ inset: 0;
width: auto;
height: auto;
+ max-width: none;
+ max-height: none;
+ margin: 0;
+ padding: 0;
background: transparent;
border: 0;
overflow: visible;
}
-/* Style the popover's ::backdrop to achieve the overlay effect and
+/* Style the dialog's ::backdrop to achieve the overlay effect and
provide visual affordances indicating that the rest of the page is inert */
.Drawer::backdrop {
background: #000;
@@ -121,7 +137,7 @@ The scroller is a horizontal grid wider than the viewport: column 1 holds the sh
.Drawer-scroller::after {
content: '';
scroll-snap-align: end;
- /* Open the popover already scrolled to this stop (drawer off-screen),
+ /* Open the drawer already scrolled to this stop (drawer off-screen),
so the JS only needs to scroll to the open position to
animate it in. */
scroll-initial-target: nearest;
@@ -190,20 +206,21 @@ A scroll-driven animation maps `--drawer-backdrop` from 1 (open) to 0 (closed) a
### 3. Open and close the drawer
-Opening is two steps: promote the popover to the top layer, then scroll the sheet into view. Closing is one step: scroll back to the spacer; an observer (step 4) hides the popover once the sheet is fully off-screen.
+Opening is two steps: show the dialog as modal, then scroll the sheet into view. Closing is one step: scroll back to the spacer; an observer (step 4) closes the dialog once the sheet is fully off-screen.
```js
const drawer = document.getElementById('drawer');
const openBtn = document.getElementById('drawer-open');
const scroller = drawer.querySelector('.Drawer-scroller');
const sheet = drawer.querySelector('.Drawer-sheet');
+const closeBtn = document.getElementById('drawer-close');
function openDrawer() {
- // Show the popover first so the element is in the top layer before
+ // Show the dialog first so the element is in the top layer before
// we trigger any scrolling. `scroll-initial-target` (set on the
// ::after spacer) places the initial scroll position at the closed
// stop, so the drawer enters the top layer already off-screen.
- drawer.showPopover();
+ drawer.showModal();
// Scroll the sheet into view. The `behavior: 'auto'` option defers
// to the CSS `scroll-behavior` property, which will be smooth unless
@@ -213,10 +230,10 @@ function openDrawer() {
}
function closeDrawer() {
- // Scroll back to the spacer. Do NOT call hidePopover() here —
+ // Scroll back to the spacer. Do NOT call close() here —
// doing so would remove the element from the top layer mid-animation
// and the close animation would not be visible. The
- // IntersectionObserver in step 4 hides the popover once the sheet
+ // IntersectionObserver in step 4 closes the dialog once the sheet
// has actually left the viewport.
scroller.scrollTo({left: scroller.offsetWidth, behavior: 'auto'});
}
@@ -226,25 +243,21 @@ function closeDrawer() {
Use an `IntersectionObserver` on the sheet — not the scroll position — as the source of truth for the drawer's state. The observer fires regardless of how the sheet moved (user swipe, programmatic scroll, snap settle), so all dismissal paths converge in the same callback.
+Because the drawer is a modal `<dialog>`, the browser makes the rest of the page inert while it is open and moves focus back to the trigger button when it closes, so these callbacks only need to close the dialog and keep `aria-expanded` in sync.
+
```js
function onDrawerOpened() {
- // Mark the rest of the page inert so keyboard and screen-reader
- // users cannot tab into content hidden behind the drawer.
- document.querySelector('main').inert = true;
openBtn.setAttribute('aria-expanded', 'true');
- // Move focus into the drawer for keyboard users.
- sheet.focus();
}
function onDrawerClosed() {
- // Hide the popover only after the close animation completes,
+ // Close the dialog only after the close animation completes,
// so the slide-out is visible to the user.
- drawer.hidePopover();
- document.querySelector('main').inert = false;
+ drawer.close();
openBtn.setAttribute('aria-expanded', 'false');
}
-// Treat "any pixel of the sheet visible inside the popover root" as
+// Treat "any pixel of the sheet visible inside the dialog" as
// "open enough to count as not closed". This threshold is intentionally
// tiny so the closed callback only fires once the sheet is truly gone.
const visibleThreshold = 1 / window.innerWidth;
@@ -258,8 +271,8 @@ const observer = new IntersectionObserver(
if (entry.intersectionRatio < visibleThreshold) onDrawerClosed();
if (entry.intersectionRatio === 1) onDrawerOpened();
},
- // root: drawer makes the popover element the intersection root,
- // so the ratio reflects the sheet's visibility within the popover
+ // root: drawer makes the dialog element the intersection root,
+ // so the ratio reflects the sheet's visibility within the dialog
// (i.e. how much of it has been swiped on-screen).
{root: drawer, threshold: [visibleThreshold, 1]},
);
@@ -272,14 +285,66 @@ observer.observe(sheet);
// Open trigger.
openBtn.addEventListener('click', openDrawer);
+// Close trigger.
+closeBtn.addEventListener('click', closeDrawer);
+
// Light-dismiss: a tap on the dimmed area (anywhere inside the
-// popover but outside the sheet) closes the drawer. We implement
-// this manually because popover="manual" disables the browser's
-// built-in light-dismiss (which would also fire mid-swipe — see step 1).
+// dialog but outside the sheet) closes the drawer. Do not use
+// closedby="any": the dialog fills the viewport, so taps land on the
+// dialog rather than its ::backdrop, and it would close without the
+// slide-out animation.
drawer.addEventListener('click', (event) => {
if (!sheet.contains(event.target)) closeDrawer();
});
+// Escape key. A modal dialog fires `cancel` on Escape; prevent the
+// instant close and slide the drawer out instead.
+// NOTE: Browsers may make `cancel` non-cancelable on repeated Escape
+// presses without user activation in between, closing the dialog instantly.
+drawer.addEventListener('cancel', (event) => {
+ if (event.cancelable) {
+ event.preventDefault();
+ closeDrawer();
+ }
+});
+```
+
+## Implementation for a drawer that also acts as a sidebar
+
+Use this implementation when the same element also becomes a regular, always-visible sidebar under certain conditions (see [Choose the drawer element](#choose-the-drawer-element)). Toggle `role` from the same media query that switches the layout (e.g. with `matchMedia()`): remove it while the element acts as a sidebar, and restore `role="dialog"` when it becomes a drawer again. This guide does not cover the sidebar layout itself.
+
+Follow the [`<dialog>` implementation](#implementation-with-dialog), with these changes:
+
+- **Markup**: `<div class="Drawer" id="drawer" popover="manual" role="dialog" aria-label="Navigation drawer">`. `popover="manual"` is REQUIRED; do not use `popover="auto"` or `"hint"`, as their built-in light-dismiss would also fire mid-swipe.
+- **Open and close**: call `showPopover()` instead of `showModal()` and `hidePopover()` instead of `close()`. The rest of the CSS and JS is unchanged.
+- **Modality**: a popover is not modal, so the code must do what a modal dialog does natively:
+ - Mark the rest of the page `inert` while the drawer is open.
+ - Apply `aria-modal="true"` while the drawer is open, and remove it when it closes.
+ - Move focus back to the trigger button after the drawer closes.
+ - Handle Escape with a `keydown` listener on `document`, since popovers do not fire `cancel`.
+
+```js
+const main = document.querySelector('main');
+
+function openDrawer() {
+ drawer.showPopover();
+ // Mark everything outside the drawer inert immediately on open (include
+ // sibling <header>/<footer> landmarks if they live outside <main>).
+ main.inert = true;
+ drawer.setAttribute('aria-modal', 'true');
+ scroller.scrollTo({left: 0, behavior: 'auto'});
+}
+
+function onDrawerClosed() {
+ // The observer also reports "closed" on page load; ignore it unless open.
+ if (!drawer.hasAttribute('aria-modal')) return;
+ drawer.hidePopover();
+ main.inert = false;
+ drawer.removeAttribute('aria-modal');
+ openBtn.setAttribute('aria-expanded', 'false');
+ openBtn.focus();
+}
+
// Escape key. Listen on document because focus may be inside the
// drawer when the user presses Escape.
document.addEventListener('keydown', (event) => {
@@ -287,7 +352,7 @@ document.addEventListener('keydown', (event) => {
});
```
-### Fallback strategies
+## Fallback strategies
Baseline status for Scroll snap: Widely available. It's been Baseline since 2020-01-15.
Supported by: Chrome 69 (Sep 2018), Edge 79 (Jan 2020), Firefox 68 (Jul 2019), and Safari 11 (Sep 2017).
@@ -295,16 +360,12 @@ Supported by: Chrome 69 (Sep 2018), Edge 79 (Jan 2020), Firefox 68 (Jul 2019), a
Baseline status for Intersection observer: Widely available. It's been Baseline since 2019-03-25.
Supported by: Chrome 58 (Apr 2017), Edge 16 (Oct 2017), Firefox 55 (Aug 2017), Safari 12.1 (Mar 2019), and Safari iOS 12.2 (Mar 2019).
-Baseline status for inert: Widely available. It's been Baseline since 2023-04-11.
-Supported by: Chrome 102 (May 2022), Edge 102 (May 2022), Firefox 112 (Apr 2023), and Safari 15.5 (May 2022).
-
-The popover API, the scroll-driven animation that fades the backdrop, and `scroll-initial-target` are progressive enhancements with simple fallbacks that can be easily implemented if wide browser support is required.
+The scroll-driven animation that fades the backdrop and `scroll-initial-target` are progressive enhancements with simple fallbacks that can be easily implemented if wide browser support is required.
-#### Backdrop fade fallback (no `animation-timeline` support):
+### Backdrop fade fallback (no `animation-timeline` support):
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
Detect with `CSS.supports('animation-timeline: scroll()')` and write `--drawer-backdrop` from a `scroll` event listener if not supported. The CSS `@supports` block in step 2 ensures the keyframes never apply in unsupported browsers, so the JavaScript value is the only writer.
@@ -319,17 +380,17 @@ if (!CSS.supports('animation-timeline: scroll()')) {
}
```
-#### Initial scroll position fallback (no `scroll-initial-target` support):
+### Initial scroll position fallback (no `scroll-initial-target` support):
Browser support for scroll-initial-target: Limited availability.
Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
Unsupported in: Firefox and Safari.
-Detect with `CSS.supports('scroll-initial-target', 'nearest')` and inside `openDrawer()`, jump-scroll the scroller to the closed position immediately after `showPopover()`. Without this, the drawer would appear instantly in the open position with no slide-in animation.
+Detect with `CSS.supports('scroll-initial-target', 'nearest')` and inside `openDrawer()`, jump-scroll the scroller to the closed position immediately after showing the drawer (`showModal()`, or `showPopover()` when it [also acts as a sidebar](#implementation-for-a-drawer-that-also-acts-as-a-sidebar)). Without this, the drawer would appear instantly in the open position with no slide-in animation.
```js
async function openDrawer() {
- drawer.showPopover();
+ drawer.showModal(); // sidebar variant: showPopover(), main.inert = true, and aria-modal="true"
if (!CSS.supports('scroll-initial-target', 'nearest')) {
// Jump-scroll to the closed stop so the scroll below
@@ -347,7 +408,7 @@ async function openDrawer() {
}
```
-#### `@property` fallback (no registered custom properties):
+### `@property` fallback (no registered custom properties):
Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.
Supported by: Chrome 85 (Aug 2020), Edge 85 (Aug 2020), Firefox 128 (Jul 2024), and Safari 16.4 (Mar 2023).
@@ -355,11 +416,14 @@ Supported by: Chrome 85 (Aug 2020), Edge 85 (Aug 2020), Firefox 128 (Jul 2024),
`@property` is only needed because the scroll-driven animation interpolates `--drawer-backdrop` between keyframes — without registration, the property would be treated as a string and would jump between 0 and 1 with no fade. If the scroll-driven animation fallback above is in place, that JavaScript writes a fresh numeric string to `--drawer-backdrop` on every scroll frame and never interpolates, so no separate `@property` fallback is needed since all browsers that support scroll-driven animations also support `@property`.
-#### Popover API fallback (no `popover` attribute support):
+### Popover API fallback (sidebar variant only):
Baseline status for the api.HTMLElement.showPopover capability: Widely available. It's been Baseline since 2024-04-16.
Supported by: Chrome 114 (May 2023), Edge 114 (Jun 2023), Firefox 125 (Apr 2024), and Safari 17 (Sep 2023).
-Because this component uses `popover="manual"` and implements dismissal entirely from JavaScript, it does not depend on the popover API's defining behaviors — light-dismiss, the `popovertarget` attribute, top-layer-managed Escape handling, or focus management. The only popover features it actually uses are top-layer promotion (via `showPopover()`) and the `::backdrop` pseudo-element.
+Baseline status for inert: Widely available. It's been Baseline since 2023-04-11.
+Supported by: Chrome 102 (May 2022), Edge 102 (May 2022), Firefox 112 (Apr 2023), and Safari 15.5 (May 2022).
+
+When the drawer [also acts as a sidebar](#implementation-for-a-drawer-that-also-acts-as-a-sidebar), it uses `popover="manual"` and implements dismissal entirely from JavaScript, so it does not depend on light-dismiss, the `popovertarget` attribute, or top-layer-managed Escape handling. Aside from top-layer promotion (`showPopover()`) and `::backdrop`, the only popover behavior it relies on is processing `autofocus` when shown.
-If wider browser support is needed, do not branch on feature detection — simply do not use popover at all. Drop the `popover="manual"` attribute, replace top-layer promotion with `position: fixed` and a high `z-index`, replace `::backdrop` with a sibling element styled identically (using the same `--drawer-backdrop` custom property), and toggle visibility from a class instead of `showPopover()`/`hidePopover()`. The rest of the component (scroll snap, the scroll-driven backdrop animation, the `IntersectionObserver`, and the dismissal handlers) is unchanged.
+If wider browser support is needed, do not branch on feature detection — simply do not use popover at all. Drop the `popover="manual"` attribute, replace top-layer promotion with `position: fixed` and a high `z-index`, replace `::backdrop` with a sibling element styled identically (using the same `--drawer-backdrop` custom property), toggle visibility from a class instead of `showPopover()`/`hidePopover()`, and call `closeBtn.focus({preventScroll: true})` in `openDrawer()` after making the drawer visible (`preventScroll` avoids scrolling the container early). The rest of the component (scroll snap, the scroll-driven backdrop animation, the `IntersectionObserver`, and the dismissal handlers) is unchanged.
diff --git a/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md b/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md
index 7416523..b808189 100644
--- a/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md
+++ b/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md
@@ -1,23 +1,22 @@
# Creating Persistent App Tours
-Onboarding tours require overlays that persist while users interact with the highlighted features. Unlike auto popovers, manual popovers do not close when the user clicks elsewhere on the page. Combining `popover="manual"` with CSS Anchor Positioning allows you to create non-modal, tethered tour steps.
+Onboarding tours require overlays that persist while users interact with the highlighted features. Unlike auto popovers, manual popovers do not close when the user clicks elsewhere on the page. Combining `popover="manual"` with CSS Anchor Positioning allows you to create non-modal, tethered tour steps. This pattern is used to introduce new/updated content. There is no explicit relationship between the popovers themselves, so dismissing the first popover doesn't assume that the user needs to immediately move to the second popover to learn about the related feature - they can find out about it when they navigate to that section of the page.
-### Recommended Implementation
+## Recommended Implementation
-#### HTML
+### HTML
```html
<div id="feature-target">Highlight this feature</div>
-<!-- MANDATORY: Enforce overlay dialog semantics and accessible name bindings -->
-<div id="tour-step" popover="manual" role="dialog" aria-labelledby="tour-title">
+<dialog id="tour-step" popover="manual" aria-labelledby="tour-title">
<!-- Assume an <h1> precedes this element in the full document outline -->
- <h2 id="tour-title">Step 1</h2>
- <p>Learn how to use this feature.</p>
+ <h2 id="tour-title">Start a review</h2>
+ <p>Begin the process by starting a review of the submitted document.</p>
<button popovertarget="tour-step" popovertargetaction="hide">Got it</button>
-</div>
+</dialog>
```
-#### CSS
+### CSS
```css
#feature-target {
anchor-name: --feature-target;
@@ -36,15 +35,21 @@ Onboarding tours require overlays that persist while users interact with the hig
}
```
-#### JavaScript
+### JavaScript
```javascript
const tourStep = document.getElementById('tour-step');
tourStep.showPopover();
+
+// At this point, as this is an initial onboarding tour popover, set the rest of the document to be inert. Ensure that the onboarding modal popover is not a child of this element, otherwise it too will be rendered inert and therefore inaccessible.
+// Ensure that inert is removed once the initial onboarding tour has finished
+const main = document.querySelector("main");
+main.inert = true;
+
// MANDATORY: Programmatically route focus into the non-modal popover so keyboard/assistive technology users immediately perceive the new context
tourStep.querySelector('button').focus();
```
-### Implementation Guidelines
+## Implementation Guidelines
* **MANDATORY:** Use `popover="manual"` to prevent the tour step from closing accidentally during user interaction.
* **MANDATORY:** Mark the container with `role="dialog"` and link its heading via `aria-labelledby`.
@@ -52,7 +57,19 @@ tourStep.querySelector('button').focus();
* **DO** use CSS Anchor Positioning to tether the tour step to the specific feature being explained.
* **DO** provide an explicit "Close" or "Next" button within the popover that uses `popovertargetaction="hide"`.
-### Fallback strategies
+## Accessibility considerations
+
+Popovers should provide sufficient context around the features they're introducing, to be understood independently. **DON'T** make the content in a popover heavily reliant on content outside of it to be understood. For example: "New feature. Click here", relies heavily on visual information that people may not have, or may not be able to access (particularly if the content outside the popover is `inert`). Instead, something like: "New chat functionality. Start a chat to review items with fellow members", is much easier to understand when read in isolation. Tour popovers should begin with a heading, so that as to provide context to the content in the popover, as well as to provide an easy way for people using screen readers to navigate to them, when used in a non-modal way.
+
+Focus must not be moved to these popovers on page load. This is to both prevent confusion from hijacking focus. It's likely that when navigating to the page, the person using the functionality may have a goal for they want to complete, therefore, tours for new features should be treated as supplemental information and not distract the user.
+
+In keeping this information supplemental, the popover should be positioned in the DOM immediately before the functionality/control it relates to. This will help people using screen readers to easily identify the relationship between the popover and related content when reading through the page. When the popover is dismissed, focus should move to the related control/functionality.
+
+Content in popovers must scale in size and remain visible when resizing text up to 200% to adhere to WCAG 1.4.4 Resize Text (Level AA). Content in popovers must remain visible when adjusting text styling and spacing with CSS to adhere to 1.4.12 Text Spacing (Level AA). Content in popovers must remain visible, or can be accessed still, when using a viewport sized to 320 by 256 CSS pixels to adhere to 1.4.10 Reflow (Level AA).
+
+Use of non-modal popovers may result in controls being obscured when they receive focus, which would result in a fail against WCAG 2.4.11 Focus Not Obscured (Minimum) (Level AA), as focused items cannot be completely obscured. While there may not be generic guidance to completely mitigate against this issue, consider strategies that adjust the position of the tooltip or its presence. This includes ensuring that tooltips do not obscure interactive elements as they receive focus via keyboard. If the tooltip is likely to obscure an interactive element when it receives focus, either change the position of the tooltip to prevent focus being obscured, or dismiss the tooltip if it is no longer relevant to the user.
+
+## Fallback strategies
### Fallbacks & browser support for Popover
@@ -67,22 +84,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -90,48 +101,84 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
-
-#### anchor-positioning
+### Fallbacks & browser support for Anchor positioning
Browser support for Anchor positioning: Limited availability.
Supported by: Safari 27 (Sep 2026).
Unsupported in: Chrome, Edge, and Firefox.
-To support browsers without anchor positioning, you can choose between using a polyfill or a pure CSS fallback.
+Without CSS Anchor Positioning, tethered elements such as `[popover]` overlays fall back to their default user-agent placement (centered in the viewport for popovers). Depending on whether spatial tethering is required for your use case, either conditionally load the polyfill or gate your positioning rules with `@supports`.
+
+#### Option 1: Polyfill (`@oddbird/css-anchor-positioning`)
+
+When the positioned element must stay spatially tethered to its trigger in unsupported browsers, conditionally load the `@oddbird/css-anchor-positioning` package.
+
+**MANDATORY:** Feature-detect support via `CSS.supports("anchor-name: --a")` (or `"anchorName" in CSSStyleDeclaration.prototype`), and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
-##### Option 1: Polyfill Fallback
-The `@oddbird/css-anchor-positioning` polyfill can be used to emulate anchor positioning. It does not support implicit anchors, so you MUST add explicit anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets instead of `position-area`.
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature-detect anchor positioning support before loading the polyfill.
+if (!CSS.supports("anchor-name: --a")) {
+ import("@oddbird/css-anchor-positioning");
+}
+```
+
+Without a bundler, import from a CDN inside a `<script type="module">`:
```html
+<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->
<script type="module">
- if (!CSS.supports('anchor-name: --foo')) {
- await import("https://unpkg.com/@oddbird/css-anchor-positioning");
+ if (!CSS.supports("anchor-name: --a")) {
+ import("https://unpkg.com/@oddbird/css-anchor-positioning");
}
</script>
```
+**Polyfill caveats:**
+- **No implicit anchors:** The polyfill does not support implicit anchor associations (such as those created by `popovertarget`, `commandfor`, `interestfor`, or `showPopover({ source })`). You **MUST** set a unique explicit `anchor-name` on each trigger and a matching `position-anchor` on the positioned element.
+- **No `position-area` with `position-try-fallbacks`:** `position-area` with `position-try-fallbacks` is not supported by the polyfill. When using the polyfill on elements needing fallbacks, position elements using `anchor()` functions on inset properties (`top`, `left`, `right`, `bottom`) with `inset: auto` instead of `position-area`.
+- **Do not wrap polyfilled rules in `@supports`:** Browsers without native anchor positioning evaluate `@supports (position-area: ...)` and `@supports (anchor-name: --a)` to `false` and discard the block before the polyfill can process it.
+
```css
-#tour-step {
- /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions instead of `position-area`. */
- left: anchor(right);
- top: anchor(top);
+.trigger {
+ /* MANDATORY: Each trigger and positioned element pair must share a unique anchor name. */
+ anchor-name: --my-trigger;
+}
+
+[popover].anchored-overlay {
+ position-anchor: --my-trigger;
+ /* MANDATORY: Use anchor() on inset properties rather than position-area when using the polyfill on elements needing position-try-fallbacks. */
+ inset: auto;
+ top: anchor(bottom);
+ left: anchor(left);
+ margin: 0;
}
```
-##### Option 2: Non-Polyfill CSS Fallback
-If you prefer not to use a polyfill, you can default the tooltip to a fixed position at the bottom of the viewport using `@supports not`.
+#### Option 2: Progressive enhancement with `@supports` (no polyfill)
+
+If you do not ship the polyfill, **DO NOT** set `inset: auto` or `margin: 0` unconditionally on a `[popover]` element that relies on `position-area` or `anchor()`. In browsers without anchor positioning, `inset: auto` overrides the user-agent centering (`inset: 0; margin: auto`) while `position-area` is ignored, leaving the popover stranded at `(0, 0)` or overlapping its trigger.
+
+Instead, gate `inset: auto` and `margin: 0` inside `@supports` for the specific positioning feature used (for example, `@supports (position-area: block-end)` or `@supports (top: anchor(bottom))`) so unsupported browsers retain the default centered popover placement, or provide a matching `@supports not (...)` fallback layout (such as a fixed bottom sheet):
```css
-@supports not (anchor-name: --foo) {
- #tour-step {
+@supports (position-area: block-end) {
+ [popover].anchored-overlay {
+ inset: auto;
+ margin: 0;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
+ }
+}
+
+@supports not (position-area: block-end) {
+ /* Optional: override default popover centering with a fixed bottom bar */
+ [popover].anchored-overlay {
position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- width: 100%;
+ inset: auto 0 0 0;
+ width: auto;
margin: 0;
- border-radius: 0;
}
}
-```
\ No newline at end of file
+```
diff --git a/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md b/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md
index b188517..6e9617d 100644
--- a/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md
+++ b/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md
@@ -2,16 +2,42 @@
Toast notifications are transient status messages. Unlike menus, they should not close when a user interacts with other parts of the page. The popover="manual" state is ideal because it lacks "light-dismiss" behavior and allows multiple notifications to coexist.
-### Implementation Guidelines
+## When to use
+
+Toast notifications must be used to provide non-critical, supplemental information about the results of an interaction, or an event (e.g. an email has been received). An example may include confirming that a form submission was successful. Notifications that require immediate attention should instead use an alternative component. Examples include inline banners, dialogs or modal dialogs. These examples surface information in a way that is easier to identify for everyone. Toasts should be used sparingly, as making them accessible to everyone means addressing complex considerations, and is the reason why some companies have opted to no longer use them, and instead, utilize the alternative aforementioned components.
+
+## Implementation guidelines
+
+Prefer persistent toast notifications that remain present until they are dismissed, except for frequent, low importance events, where the friction persistence creates outweighs the value of the information provided. In those cases, do evaluate whether toasts actually add to the user experience in general — in some cases it may be preferable to not have them at all. If using a pattern that does dismiss toasts after a short period of time, check whether focus is on a control in the toast before dismissal. If the user is focused on a control inside the toast, pause dismissal until focus has left the toast.
* **MANDATORY:** Use popover="manual" so the notification stays visible until explicitly closed or timed out by a script.
+* **MANDATORY:** Ensure that the information in the toast can be identified by other means, so that if it is part of a pattern that disappears after a short period of time, people can still identify the information without the toast being present.
* **DO** use a container to manage the stacking of multiple toasts. Since popovers in the Top Layer ignore parent z-index, you must position them individually or within a common layout group.
-* **DO** use sibling-index() to add margin between toast notifications so that items lower in the stack are visible.
+* **DO** add toast notifications consistently to the same container in the page, so that people using assistive technologies can consistently locate them.
+* **DO** make the container a region, with an accessible name, so that it can be easily identified using a screen reader. For example: `<div role="region" aria-label="Notifications"></div>`.
+* **DO** use `ariaNotify()` to announce the content present in toasts that are displayed. This ensures that people using screen readers, who cannot see the screen, are aware of the presence of toast messages
+* **DO** ensure that only the toast's visible text is announced as part of the `ariaNotify()` and not the names of any controls. If actions are available in the toast (aside from a close control), append "Actions available" to the end of the announcement.
* **DO** provide an explicit "Close" button within the toast using popovertargetaction="hide".
-* **DO** use JavaScript for auto-dismissal timers (e.g., calling hidePopover() after 3000ms).
-* **DO** utilize transition-behavior: allow-discrete to animate the entry and exit from the Top Layer.
+* **DO** ensure that a toast's dismiss button is keyboard-focusable (without automatically stealing focus when the toast appears), so keyboard users can navigate to the toast region and dismiss notifications.
+* **DO** manage focus when a user manually dismisses a currently focused toast: move focus to the next remaining toast in the stack, or—if no toasts remain—return focus to the user's prior focus location (or the control that triggered the toast).
+* **DO** declare `transition-behavior: allow-discrete` as a separate property after `transition` (rather than inside the `transition` shorthand) to animate entry and exit from the Top Layer without older browsers ignoring the `transition` declaration.
+* **DO** provide a non-animated version using the `prefers-reduced-motion` media query
+* **DO** ensure that toast messages scale in size, and that all toast content remains visible when resizing text up to 200% to adhere to WCAG 1.4.4 Resize Text (Level AA)
+* **DO** ensure that all toast content remains visible when adjusting text styling and spacing with CSS to adhere to 1.4.12 Text Spacing (Level AA)
+* **DO** ensure that all toast content remains visible, or can be accessed still, when using a viewport sized to 320 by 256 CSS pixels to adhere to 1.4.10 Reflow (Level AA)
+
+* **DON'T** surface toasts in scenarios where focus redirection may be used at the same time. The focus redirection may cancel out the toast announcements, resulting in people missing information.
+* **DON'T** use toasts in modal dialogs. Content outside of the dialog will be inert and unavailable to assistive technologies. Placing the toast in a modal dialog, separate from the existing toast container makes it difficult to locate, and may lead to people not being able to locate it.
+* **DON'T** surface toast notifications in the background while a modal dialog is open. It's likely the notification will be missed. Instead, suppress the notification until the modal dialog is dismissed.
+* **DON'T** include controls in toast notifications that perform actions not already permanently available outside the toast notifications. Controls in toasts should be used sparingly, and only provided as a shortcut for actions already available via the UI.
-### Fallback Strategies
+## Optional: Usability & accessibility improvements
+
+* **Surface previous toasts**: Provide a way for people to access a list of past toast messages. This can help people who may encounter difficulty in remembering what the toast informed them, or reduce anxiety for people who inadvertently dismissed a toast message.
+* **Customize toast notifications**: Provide a way for people to customize which toast notifications are provided. This can help to ensure that information provided to people is relevant, reducing distractions and confusion.
+* **Use an alternative way to communicate toasts are present**: It is recommended that there are multiple ways to communicate that a toast has been made visible. An example of this may be a brief sound effect (which could be turned off). This will help people using screen magnification software, who may otherwise find it difficult to identify that toasts are present.
+
+## Fallback strategies
### Fallbacks & browser support for Popover
@@ -26,39 +52,134 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Fallbacks & browser support for ariaNotify()
+
+Baseline status for ariaNotify(): Newly available. It's been Baseline since 2026-09-14.
+Supported by: Chrome 141 (Sep 2025), Edge 141 (Oct 2025), Firefox 150 (Apr 2026), and Safari 27 (Sep 2026).
+
+Baseline status for ariaNotify(): Newly available. It's been Baseline since 2026-09-14.
+Supported by: Chrome 141 (Sep 2025), Edge 141 (Oct 2025), Firefox 150 (Apr 2026), and Safari 27 (Sep 2026).
+
+Use an ARIA live region, ensuring that the container is present in the page on load, and then add the messages to the live region container when relevant.
+
+```html
+<!-- Pre-populated hidden live region container -->
+<div id="notification" aria-live="assertive"></div>
+```
+
+This content will be present in the DOM, and can be read by a screen reader after the message has been announced. Therefore, in order to provide context to this region, when the live region has content, add in text immediately before the container to provide context to the announcement. This will help people understand the purpose of the content if they identify it when reading the page.
+
+```html
+<p class="inclusively-hidden">Screen reader announcements</p>
+<!-- Pre-populated hidden live region container -->
+<div id="notification" aria-live="assertive">
+ Dynamic announcement injected into the existing container.
+</div>
+```
+
+### Fallbacks & browser support for Anchor positioning
+
+Browser support for Anchor positioning: Limited availability.
+Supported by: Safari 27 (Sep 2026).
+Unsupported in: Chrome, Edge, and Firefox.
+
+Without CSS Anchor Positioning, tethered elements such as `[popover]` overlays fall back to their default user-agent placement (centered in the viewport for popovers). Depending on whether spatial tethering is required for your use case, either conditionally load the polyfill or gate your positioning rules with `@supports`.
+
+#### Option 1: Polyfill (`@oddbird/css-anchor-positioning`)
+
+When the positioned element must stay spatially tethered to its trigger in unsupported browsers, conditionally load the `@oddbird/css-anchor-positioning` package.
+
+**MANDATORY:** Feature-detect support via `CSS.supports("anchor-name: --a")` (or `"anchorName" in CSSStyleDeclaration.prototype`), and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature-detect anchor positioning support before loading the polyfill.
+if (!CSS.supports("anchor-name: --a")) {
+ import("@oddbird/css-anchor-positioning");
+}
+```
+
Without a bundler, import from a CDN inside a `<script type="module">`:
```html
+<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->
<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
+ if (!CSS.supports("anchor-name: --a")) {
+ import("https://unpkg.com/@oddbird/css-anchor-positioning");
}
</script>
```
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+**Polyfill caveats:**
+- **No implicit anchors:** The polyfill does not support implicit anchor associations (such as those created by `popovertarget`, `commandfor`, `interestfor`, or `showPopover({ source })`). You **MUST** set a unique explicit `anchor-name` on each trigger and a matching `position-anchor` on the positioned element.
+- **No `position-area` with `position-try-fallbacks`:** `position-area` with `position-try-fallbacks` is not supported by the polyfill. When using the polyfill on elements needing fallbacks, position elements using `anchor()` functions on inset properties (`top`, `left`, `right`, `bottom`) with `inset: auto` instead of `position-area`.
+- **Do not wrap polyfilled rules in `@supports`:** Browsers without native anchor positioning evaluate `@supports (position-area: ...)` and `@supports (anchor-name: --a)` to `false` and discard the block before the polyfill can process it.
```css
-[popover]:is(:popover-open, .\:popover-open) {
- display: block;
+.trigger {
+ /* MANDATORY: Each trigger and positioned element pair must share a unique anchor name. */
+ anchor-name: --my-trigger;
+}
+
+[popover].anchored-overlay {
+ position-anchor: --my-trigger;
+ /* MANDATORY: Use anchor() on inset properties rather than position-area when using the polyfill on elements needing position-try-fallbacks. */
+ inset: auto;
+ top: anchor(bottom);
+ left: anchor(left);
+ margin: 0;
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
+#### Option 2: Progressive enhancement with `@supports` (no polyfill)
-#### sibling-index()
+If you do not ship the polyfill, **DO NOT** set `inset: auto` or `margin: 0` unconditionally on a `[popover]` element that relies on `position-area` or `anchor()`. In browsers without anchor positioning, `inset: auto` overrides the user-agent centering (`inset: 0; margin: auto`) while `position-area` is ignored, leaving the popover stranded at `(0, 0)` or overlapping its trigger.
-* **Guidance:** If sibling-index() is not supported, use the `+` operator to add margin manually. I.e. `popover + popover { margin-top: 1rem }`
+Instead, gate `inset: auto` and `margin: 0` inside `@supports` for the specific positioning feature used (for example, `@supports (position-area: block-end)` or `@supports (top: anchor(bottom))`) so unsupported browsers retain the default centered popover placement, or provide a matching `@supports not (...)` fallback layout (such as a fixed bottom sheet):
-#### anchor-positioning
+```css
+@supports (position-area: block-end) {
+ [popover].anchored-overlay {
+ inset: auto;
+ margin: 0;
+ position-area: block-end span-inline-end;
+ position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline;
+ }
+}
-* **Guidance:** Use the [CSS Anchor Positioning Polyfill](https://github.com/oddbird/css-anchor-positioning). For a non-polyfill fallback, default the tooltip to a fixed position at the bottom of the viewport using `@supports not (anchor-name: --foo)`.
+@supports not (position-area: block-end) {
+ /* Optional: override default popover centering with a fixed bottom bar */
+ [popover].anchored-overlay {
+ position: fixed;
+ inset: auto 0 0 0;
+ width: auto;
+ margin: 0;
+ }
+}
+```
+
+#### sibling-index()
+
+* **Guidance:** If sibling-index() is not supported, use the `+` operator to add margin manually. I.e. `popover + popover { margin-top: 1rem }`
#### transition-behavior
-* **Guidance:** If transition-behavior is not supported, use JavaScript to add animation via classes as the toast element transitions in and out.
\ No newline at end of file
+* **Guidance:** If transition-behavior is not supported, use JavaScript to add animation via classes as the toast element transitions in and out.
diff --git a/skills/modern-web-guidance/guides/ui-components/progress-ring.md b/skills/modern-web-guidance/guides/ui-components/progress-ring.md
index c4d42d8..6c4f5fe 100644
--- a/skills/modern-web-guidance/guides/ui-components/progress-ring.md
+++ b/skills/modern-web-guidance/guides/ui-components/progress-ring.md
@@ -19,15 +19,20 @@ See the `spinner` (via `npx -y modern-web-guidance@latest retrieve "spinner"`) f
Use a wrapper to hold both the visual ring and the optional center content. The `<progress>` element remains the semantic source of truth. Use a utility class to visually hide the native progress bar while keeping it accessible.
```html
-<div class="ring-wrapper">
+<div class="progress-ring-wrapper">
<progress value="75" max="100" aria-label="Task progress" class="progress-ring"></progress>
- <!-- Optional: Content to display in the center -->
- <div class="ring-content">
+ <!-- Optional: Content to display in the center. Hidden from assistive
+ technologies because it repeats the value of the <progress> element. -->
+ <div class="progress-ring-content" aria-hidden="true">
75%
</div>
</div>
```
+Hide the center content from assistive technologies with `aria-hidden="true"`. The `<progress>` element already exposes its value, so screen readers would otherwise announce it twice.
+
+If the center content shows the value in another form, such as "3 of 5 files" or a percentage, set the same text in `aria-valuetext` on the `<progress>` element whenever you update it, otherwise screen readers only get the number.
+
### 2. Styles
#### Hiding Native UI
@@ -35,19 +40,19 @@ To style the `<progress>` element as a progress ring, first hide the default bro
```css
/* Hide native bars */
-progress.loading-spinner:indeterminate::-webkit-progress-bar {
+progress.progress-ring::-webkit-progress-bar {
display: none;
background: none;
}
-progress.loading-spinner:indeterminate::-webkit-progress-value {
+progress.progress-ring::-webkit-progress-value {
display: none;
background: none;
}
-progress.loading-spinner:indeterminate::-moz-progress-bar {
+progress.progress-ring::-moz-progress-bar {
display: none;
background: none;
}
-progress.loading-spinner:indeterminate::slider-fill {
+progress.progress-ring::slider-fill {
display: none;
background: none;
}
@@ -55,7 +60,7 @@ progress.loading-spinner:indeterminate::slider-fill {
#### Container and Ring
-The wrapper provides the positioning context. The `<progress>` element handles the visual gradient.
+The wrapper provides the positioning context. The `<progress>` element handles the visual gradient. Forced colors mode removes background gradients, so in `@media (forced-colors: active)`, opt the ring out with `forced-color-adjust: none` and draw it with system colors, or the ring disappears.
```css
.progress-ring-wrapper {
@@ -85,6 +90,13 @@ progress.progress-ring {
background-clip: border-area;
border: var(--thickness) solid transparent;
background-origin: border-box;
+
+ @media (forced-colors: active) {
+ /* Keeps the gradient, which forced colors mode removes, and draws it in system colors */
+ forced-color-adjust: none;
+ --fill-color: CanvasText;
+ --track-color: Canvas;
+ }
}
.progress-ring-content {
diff --git a/skills/modern-web-guidance/guides/ui-components/scrollspy.md b/skills/modern-web-guidance/guides/ui-components/scrollspy.md
index d8b1595..1bf1a49 100644
--- a/skills/modern-web-guidance/guides/ui-components/scrollspy.md
+++ b/skills/modern-web-guidance/guides/ui-components/scrollspy.md
@@ -41,16 +41,16 @@ nav a:target-current {
</nav>
<main>
- <!-- MANDATORY: Each section must have a unique ID matching a link fragment in the <nav>. -->
- <section id="intro">
+ <!-- MANDATORY: Each section must have a unique ID matching a link fragment in the <nav> and tabindex="-1" so it can receive focus. -->
+ <section id="intro" tabindex="-1">
<h2>Introduction</h2>
<!-- content -->
</section>
- <section id="features">
+ <section id="features" tabindex="-1">
<h2>Features</h2>
<!-- content -->
</section>
- <section id="pricing">
+ <section id="pricing" tabindex="-1">
<h2>Pricing</h2>
<!-- content -->
</section>
@@ -72,6 +72,21 @@ nav a:target-current {
</script>
```
+## Accessibility considerations
+
+To ensure that people can navigate the scrollable region after selecting an anchor element, apply the corresponding element with a `tabindex="-1"` attribute. This will allow the element to receive focus, and allow people using a keyboard to scroll the container, or easily navigate from that content.
+
+```html
+<li><a href="#section-2">Section 2</a></li>
+…
+<!-- Adding a tabindex="-1" attribute to the section target will mean that it can receive focus after being navigated to -->
+<section id="section-2" tabindex="-1">
+ <h2>Section 2</h2>
+</section>
+```
+
+To ensure consistent operability across different browsers and assistive technology combinations, if the scrollable container is not the `<body>` element, ensure that it can receive focus (by applying `tabindex="0"`), and has an accessible name that describes the content, along with an appropriate role (such as `role="region"`), if it does not already have an implicit role (which elements like `<main>` do).
+
## Best Practices
- **DO** use `scroll-target-group: auto` on a dedicated container for navigation links: This ensures the browser knows which links should be tracked.
diff --git a/skills/modern-web-guidance/guides/ui-components/spinner.md b/skills/modern-web-guidance/guides/ui-components/spinner.md
index 28c582b..0c204ec 100644
--- a/skills/modern-web-guidance/guides/ui-components/spinner.md
+++ b/skills/modern-web-guidance/guides/ui-components/spinner.md
@@ -47,7 +47,7 @@ progress.loading-spinner:indeterminate::slider-fill {
```
#### Spinner Ring and Trail
-The spinner uses a `conic-gradient` to create a visual trail.
+The spinner uses a `conic-gradient` to create a visual trail. Forced colors mode removes background gradients, so in `@media (forced-colors: active)`, opt the spinner out with `forced-color-adjust: none` and draw it with system colors, or the spinner disappears.
```css
@property --arc-start {
@@ -72,7 +72,7 @@ progress.loading-spinner:indeterminate {
--_to: calc(90deg + var(--arc-end, 158deg));
--size: 40px;
--thickness: 2px;
- --spinner-color: #3b82f6;
+ --spinner-color: #2563eb;
--track-color: #e2e5e7;
--spinner-duration: 1.5s;
--_used-spinner-duration: var(--spinner-duration);
@@ -100,6 +100,13 @@ progress.loading-spinner:indeterminate {
/* ... fallback for background-clip: border-area ... */
+ @media (forced-colors: active) {
+ /* Keeps the gradient, which forced colors mode removes, and draws it in system colors */
+ forced-color-adjust: none;
+ --spinner-color: CanvasText;
+ --track-color: Canvas;
+ }
+
/* The dash animation is only included if @property is supported */
animation:
progress-spin var(--_used-spinner-duration) linear infinite
@@ -130,14 +137,17 @@ progress.loading-spinner:indeterminate {
#### Respecting Motion Preferences
-Users with motion sensitivities may find fast-spinning elements disorienting. Always respect the `prefers-reduced-motion` media query. Set the internal `--_used-spinner-duration` property to override the user's `--spinner-duration` value.
+Users with motion sensitivities may find fast-spinning elements disorienting. Always respect the `prefers-reduced-motion` media query. Set the internal `--_used-spinner-duration` property to override the user's `--spinner-duration` value, using the same selector as the spinner rule so that the override applies, and drop the dash animation so that only a slow rotation remains.
```css
@media (prefers-reduced-motion: reduce) {
- .loading-spinner {
+ progress.loading-spinner:indeterminate {
/* Slow down the animation significantly rather than stopping it entirely,
so the user still knows that the process is active. */
--_used-spinner-duration: 6s;
+ /* Drops the dash animation, so the arc keeps a fixed length */
+ --progress-dash-animation: ;
+ --arc-end: 158deg;
}
}
```
diff --git a/skills/modern-web-guidance/guides/ui-components/stack-drill-down.md b/skills/modern-web-guidance/guides/ui-components/stack-drill-down.md
index 985208c..29da23a 100644
--- a/skills/modern-web-guidance/guides/ui-components/stack-drill-down.md
+++ b/skills/modern-web-guidance/guides/ui-components/stack-drill-down.md
@@ -34,7 +34,9 @@ Each view is a `.Stack-view` direct child of `.Stack` (the snap target) with a `
of this section of the app. No back button — there is nothing
behind the root in the stack. -->
<div class="Stack-view" inert>
- <div class="Stack-viewContent">
+ <!-- tabindex="-1" lets focus move to the root's content when there is
+ no link or back button to focus (step 7). -->
+ <div class="Stack-viewContent" tabindex="-1">
<!-- Root content; includes <a href> links that drill in. -->
</div>
</div>
@@ -44,10 +46,12 @@ Each view is a `.Stack-view` direct child of `.Stack` (the snap target) with a `
<div class="Stack-view" inert>
<div class="Stack-viewContent">
<header>
- <!-- DO include a back button. The swipe gesture only works on
- touch — keyboard and pointer users need an explicit control. -->
- <button class="back" aria-label="Back"></button>
- <!-- Title / breadcrumb / etc. -->
+ <!-- DO include a back button. The swipe gesture is not
+ discoverable or available to all users, so keyboard and
+ pointer users need an explicit control. Name it after the
+ view it returns to (step 7). -->
+ <button class="back" aria-label="Back to Inbox"></button>
+ <h2>Message</h2>
</header>
<main>
<!-- View content; may include further drill-down <a href> links. -->
@@ -60,8 +64,8 @@ Each view is a `.Stack-view` direct child of `.Stack` (the snap target) with a `
<div class="Stack-view">
<div class="Stack-viewContent">
<header>
- <button class="back" aria-label="Back"></button>
- <!-- ... -->
+ <button class="back" aria-label="Back to Message"></button>
+ <h2><!-- ... --></h2>
</header>
<main><!-- ... --></main>
</div>
@@ -135,7 +139,10 @@ The stack is a horizontal grid where each child view is exactly the width of the
.Stack-viewContent {
width: 100%;
height: 100%;
- background-color: #fff;
+ /* Set the text color with the background color so the pair keeps its
+ contrast when the page uses a dark color scheme. */
+ background-color: Canvas;
+ color: CanvasText;
/* Each view scrolls its own content vertically, independent of the
stack's horizontal scroll. */
overflow-y: auto;
@@ -251,7 +258,9 @@ function createRootView() {
const view = document.createElement('div');
view.className = 'Stack-view';
view.innerHTML = `
- <div class="Stack-viewContent">
+ <!-- tabindex="-1" lets step 7 focus the root's content when there is
+ no link to return focus to. -->
+ <div class="Stack-viewContent" tabindex="-1">
<!-- Root content. Include <a href> elements pointing at URL paths
that resolveUrl() accepts, to enable drill-down from here. -->
</div>
@@ -262,16 +271,17 @@ function createRootView() {
// Build a drill-down view DOM element from the resolved route data.
// Customize the inner content freely, but DO preserve the .Stack-view
// / .Stack-viewContent wrapper structure and DO include a back button
-// (the swipe gesture only works on touch).
+// (the swipe gesture is not discoverable or available to all users).
function createDrillDownView(routeData) {
const view = document.createElement('div');
view.className = 'Stack-view';
view.innerHTML = `
<div class="Stack-viewContent">
<header>
+ <!-- Step 7 names this button after the view it returns to. -->
<button class="back" aria-label="Back"></button>
- <!-- Title, breadcrumb, or other view chrome derived from
- routeData. -->
+ <h2></h2>
+ <!-- Breadcrumb or other view chrome derived from routeData. -->
</header>
<main>
<!-- View body, also from routeData. Include further <a href>
@@ -280,6 +290,9 @@ function createDrillDownView(routeData) {
</main>
</div>
`;
+ // Set the title as text so it can't inject markup. (`title` is an
+ // example field; use whatever your routeData provides.)
+ view.querySelector('h2').textContent = routeData.title;
return view;
}
@@ -488,6 +501,11 @@ The handler is extracted into a standalone `onActiveViewChanged` function so the
```js
function onActiveViewChanged(currentView) {
+ // Note whether focus is in the stack before views are made inert or
+ // removed, so the focus fallback below only moves focus that would
+ // otherwise be lost, and never moves it on page load.
+ const focusWasInStack = stack.contains(document.activeElement);
+
// Walk the stack in DOM order to update each view's role:
// - Views at or before currentView stay in the DOM but get
// `inert` (except currentView) so focus, pointer events, and
@@ -527,6 +545,24 @@ function onActiveViewChanged(currentView) {
history.go(currentViewDepth - currentDepth);
}
+ // Name the active view in the title, and use the app name alone for the
+ // root. Each drill-down adds a history entry, and the title is what the
+ // history list, the tab and screen readers use to tell them apart.
+ // ('Mail' is an example app name.)
+ const viewTitle = currentView.querySelector('h2')?.textContent;
+ document.title = viewTitle ? `${viewTitle} | Mail` : 'Mail';
+
+ // Name the back button after the view it returns to: the previous view
+ // in the stack, or the root view after a deep link. Focus lands on it
+ // after a drill-down, so "Back" alone tells screen reader users nothing
+ // about where they are. ('Inbox' is the example root title.)
+ const back = currentView.querySelector('.back');
+ if (back) {
+ const parentTitle =
+ currentView.previousElementSibling?.querySelector('h2')?.textContent ?? 'Inbox';
+ back.setAttribute('aria-label', `Back to ${parentTitle}`);
+ }
+
// Restore focus on the now-active view:
// - If we recorded which link the user activated to drill out
// of this view, return focus there so a swipe-back lands them
@@ -537,11 +573,17 @@ function onActiveViewChanged(currentView) {
// snap container to bring the focused element into view, which
// fights the snap and can land the user mid-snap.
const stored = returnFocus.get(currentView);
- if (stored) {
+ if (stored?.isConnected) {
stored.focus({preventScroll: true});
returnFocus.delete(currentView);
} else if (currentView !== rootView) {
currentView.querySelector('.back')?.focus({preventScroll: true});
+ } else if (focusWasInStack && !currentView.contains(document.activeElement)) {
+ // The root has no back button, and after a deep link or a pruned view
+ // there is no stored link either, so focus the root's content. Otherwise
+ // focus would stay in a removed or inert view and fall to <body>, and
+ // keyboard and screen reader users would restart from the top of the page.
+ currentView.querySelector('.Stack-viewContent')?.focus({preventScroll: true});
}
}
@@ -591,12 +633,14 @@ updateFromHistoryState(history.state, 'instant');
- **DO** push a history entry on every drill-down and handle `popstate` so the OS-level Back gesture and the browser back/forward buttons work. This is what makes the pattern feel like a native app.
- **DO** reconcile history from the active-view-changed handler when a swipe-back lands on a view whose depth doesn't match `currentDepth`. Without this, a subsequent OS Back returns the user somewhere unexpected because the browser's history cursor is out of sync with what's on screen.
- **DO** prune views the user swiped past from the DOM. A long drill-down session can otherwise accumulate dozens of detached subtrees. The cached URL path in `entriesByDepth` is enough to rebuild any view if forward navigation returns to it.
+- **DO** make sure focus ends up inside the active view after every active-view change, including Back from a deep link and jumps to the root. If there is no stored link and no back button, focus the view's `.Stack-viewContent` (given `tabindex="-1"`). Focus left in a removed or `inert` view falls to `<body>`.
+- **DO** update `document.title` to name the active view on every active-view change. Each drill-down adds a history entry, and the title is what the browser's history list, the tab and screen readers use to tell those entries apart.
- **DO** call `.focus({preventScroll: true})` when restoring focus inside the stack. The default `preventScroll: false` makes the browser scroll the focus target into view, which fights the snap container and can land the user mid-snap.
- **DO** preserve cmd/ctrl/middle-click on internal links so URLs remain shareable and openable in a new tab.
- **DO** use `behavior: 'instant'` for multi-step history jumps AND for spatial-forward popstate transitions (`toIdx > fromIdx`). Multi-step jumps would otherwise fire `scrollsnapchange` at every intermediate snap and do N rounds of inert/focus/history work. Forward popstates are often spurious — iOS Safari treats edge swipes as browser forward even with `overscroll-behavior-x: none` set, and an instant swap is much less misleading than animating a "drilldown" the user didn't initiate. The user-initiated drill-down path (`drillDown`) is unaffected because it scrolls directly, not via `popstate`.
- **DO** respect `prefers-reduced-motion`: declare `scroll-behavior: smooth` only inside `@media (prefers-reduced-motion: no-preference)` and call `scrollTo` / `scrollBy` with `behavior: 'auto'` (not `'smooth'`) so the OS-level preference takes effect without per-call JS branching. Hard-coding `behavior: 'smooth'` bypasses the user's setting.
- **DO** render real `<a href>` elements as drill-down triggers, not `<button onclick>` or `<div>`. Real anchors get URL preview on hover, shareability, middle-click, screen-reader role, and SEO for free.
-- **DO** include an explicit back button in every drill-down view. The swipe gesture only works on touch — keyboard, pointer, and desktop users need a visible affordance.
+- **DO** include an explicit back button in every drill-down view. The swipe gesture is not discoverable or available to all users — keyboard, pointer, and desktop users need a visible affordance. Horizontal arrow keys and trackpad swipes can also scroll the stack.
- **DO NOT** call `history.pushState` from the `popstate` handler — that pushes *new* entries while the user is trying to go back and breaks the browser back button.
- **DO NOT** drive the parallax with a `scroll` event listener when scroll-driven animations are available. The CSS path runs on the compositor; a JS scroll listener runs on the main thread and will visibly drop frames during the gesture.
- **DO NOT** mutate views you removed from the DOM after a swipe-back. Treat `entriesByDepth` as the canonical record: a pruned entry has `view: null` and is rebuilt on demand in `updateFromHistoryState`.
@@ -663,9 +707,8 @@ if (!('onscrollsnapchange' in HTMLElement.prototype)) {
#### Scroll-driven animations
-Browser support for Scroll-driven animations: Limited availability.
-Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), and Safari 26 (Sep 2025).
-Unsupported in: Firefox.
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
The scroll-driven parallax / dim / shadow effect is a progressive enhancement on top of the navigation core. The CSS `@supports (animation-timeline: view())` gate (shown in step 2) confines the animation to supporting browsers; everywhere else the views simply cut between snap stops with no transition. The component is fully functional without the parallax — snap, history sync, focus management, and `inert` all still work.
diff --git a/skills/modern-web-guidance/guides/ui-components/tabs.md b/skills/modern-web-guidance/guides/ui-components/tabs.md
new file mode 100644
index 0000000..e3501e5
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/tabs.md
@@ -0,0 +1,371 @@
+# Tabbed interfaces
+
+## Basic markup
+
+Instead of manually implementing a roving tabindex or ARIA activedescendant pattern to meet the focus management requirement of the ARIA `tablist` role, we can use `focusgroup` which has a `tablist` behavior and automatically assigns the right roles (`tablist` on the container and `tab` on its focusable children).
+
+```html
+<div class="tabs">
+ <div focusgroup="tablist" aria-label="Web platform technologies">
+ <button type="button" id="html-tab" aria-selected="true" focusgroupstart>HTML</button>
+ <button type="button" id="css-tab">CSS</button>
+ <button type="button" id="js-tab">JavaScript</button>
+ </div>
+ <div role="tabpanel" aria-labelledby="html-tab" tabindex="0"><!-- content for HTML tab --></div>
+ <div role="tabpanel" aria-labelledby="css-tab" hidden="until-found"><!-- content for CSS tab --></div>
+ <div role="tabpanel" aria-labelledby="js-tab" hidden="until-found"><!-- content for JavaScript tab --></div>
+</div>
+```
+
+DO NOT use this or the WAI-ARIA tabs pattern for page navigation, even if it is intended to be presented as a tabbed interface.
+
+Tablist:
+- Prefer `<button>` for the tabs to avoid needing to reimplement button-like behavior. Add `type=button` to avoid unexpected submitter behavior if nested within a form.
+- Use `aria-labelledby` or `aria-label` to give the tablist an accessible name.
+- Use `aria-selected` to indicate which tab is currently selected.
+
+Tab panels:
+- Set `role=tabpanel` on the tab panels and use `aria-labelledby` or `aria-label` to give the panel an accessible name (e.g. `aria-labelledby` can reference the associated tab).
+- Do not add `aria-controls` to the tabs: no screen reader uses it.
+- Use `hidden="until-found"` to hide tab panels whose tab is not actively selected while still keeping them searchable by the browser’s find-in-page feature. Use `hidden` with no value to remove the content from the browser's search in-page feature as well.
+- When using `hidden="until-found"`, use the `beforematch` event to sync the tab & tab panel selection state when find-in-page makes a different tab active.
+- Set `tabindex=0` on the visible tab panel if it contains no focusable elements, and remove it from hidden panels.
+
+- MANDATORY: Render the initial state in the HTML: `hidden` on every panel except the selected one, and `aria-selected="true"` on the selected tab. Otherwise every panel shows until script runs, overlapping when they share a grid cell.
+
+## Keyboard interaction
+
+When it comes to how tabs become selected, one can either make _selection follow focus_ or allow the user to move focus between tabs and perform _selection by activation_.
+
+Default to _selection follows focus_.
+It saves a keypress per tab, is more discoverable, and matches native radio groups.
+Use selection by activation instead when showing a panel has a cost the user should opt into, since arrowing from the first tab to the fifth would pay it for every tab along the way:
+- Showing the panel is not instant: content is fetched on demand, or rendering it is noticeably slow.
+- Selecting a tab has side effects: it changes the URL or history, sends analytics, starts media, or saves state.
+- The panel shifts the layout significantly (e.g. panels of very different heights push the rest of the page around).
+
+With either pattern, focus entering the group must land on the selected item. By default it returns to the last focused item instead, which is wrong once selection can change without focus (find-in-page, script).
+Use `nomemory` and move `focusgroupstart` to the selected tab:
+
+```html
+<div focusgroup="tablist nomemory" aria-label="Web platform technologies">
+```
+
+```js
+for (const tab of tabs) {
+ tab.ariaSelected = tab === selected;
+ tab.toggleAttribute('focusgroupstart', tab === selected);
+}
+```
+
+## Styling
+
+### Indicating the selected tab
+
+Style the selected tab from `aria-selected`, so the visual state can never disagree with the accessible one.
+Do not apply any styling that changes the dimensions of the tab (e.g., `padding`, `border`, `margin`, `font-size`, `font-weight`, etc).
+
+- MANDATORY: Do not indicate the selected tab with color alone (WCAG 1.4.1). Add a shape, such as an underline.
+- Draw the underline with a border on a pseudo-element. DO NOT use `box-shadow` or a background: forced colors mode removes both, leaving no indicator.
+
+```css
+[role="tab"] {
+ position: relative;
+}
+
+[aria-selected="true"] {
+ color: var(--accent);
+
+ /* Example: a 3px underline that takes no space */
+ &::after {
+ content: "";
+ position: absolute;
+ inset: auto 0 0;
+ border-block-end: 3px solid var(--accent);
+ }
+}
+```
+
+To animate the underline between tabs, move the pseudo-element to the tablist and tether it to the selected tab with anchor positioning. See `anchor-positioning-tab-underline` (via `npx -y modern-web-guidance@latest retrieve "anchor-positioning-tab-underline"`) for details.
+
+
+- DO NOT put padding, borders, margins, or backgrounds on the panel element itself. `hidden=until-found` does not use `display: none`: it only hides the panel's contents, so a hidden panel still renders its padding, border, margin, and background as an empty strip. Put these styles on a child wrapper inside the panel instead.
+- `hidden=until-found` panels still participate in grid and flex layout, so `gap` adds space for every hidden panel. Place all panels in the same grid cell, or avoid `gap` between panels.
+
+See `search-hidden-content` (via `npx -y modern-web-guidance@latest retrieve "search-hidden-content"`) for more details.
+
+## Handling tabs that don’t fit
+
+Keep tabs on a single row. DO NOT wrap them onto multiple rows: wrapped rows make the tab order and the selected tab hard to follow.
+When the tabs are wider than the available space, either scroll the tablist or move the tabs that don’t fit into a popup menu.
+Optionally, also shrink the inactive tabs, so more tabs fit before either kicks in.
+
+1. **Scrolling** keeps every tab in the tablist and in the keyboard order, and works with touch swiping. It needs no script beyond selection. Use it by default, and always on touch-first interfaces.
+2. **An overflow menu** shows the names of all hidden tabs at once, in a list, without scrolling. Use it when there are a few primary tabs and a tail of less used ones, and users mostly use a pointer. It needs script to detect overflow.
+3. **Shrinking inactive tabs** truncates their labels, so it suits tabs the user creates (e.g. open documents in an editor) better than a fixed set of tabs with short labels. Combine it with scrolling or an overflow menu.
+
+### Strategy 1: scrolling
+
+1. Make the tablist a horizontal scroll container: `display: flex`, `overflow-x: auto`, and `flex: none` on the tabs so they never shrink (unless combined with strategy 3).
+2. Optional: snap to tab edges with `scroll-snap-type: inline proximity` on the tablist and `scroll-snap-align: start` on the tabs. Use `proximity`, not `mandatory`, so the user can still stop between tabs.
+3. Hide the scrollbar and fade out each edge of the tablist that has more tabs beyond it, as described below. A fade suits a row of tabs better than a shadow, and works on any background. See `scrollability-affordance-hints` (via `npx -y modern-web-guidance@latest retrieve "scrollability-affordance-hints"`) for more details on scrollability hints.
+4. On every selection change, scroll the selected tab into view with `scrollIntoView({ block: 'nearest', inline: 'nearest', container: 'nearest' })`. `container: 'nearest'` scrolls only the tablist, not the page. Clicking a partially visible tab then reveals it along with part of the next one, so mouse users without a horizontal scroll wheel can still reach every tab. It also covers selection without focus, such as find-in-page.
+
+#### Fading the edges
+
+Fade the content with a mask on the scroller itself: an opaque layer minus a gradient band at each end. Masking only the bands keeps everything else visible, including a focus outline on the scroller, which a single gradient clipped to the border box would hide. Animate each band's size with a scroll-driven animation on the scroller's own scroll position: each fade grows from 0 as the user scrolls away from that end, and shrinks back to 0 as they reach the other end. When the content fits, the scroll timeline is inactive and there is no fade.
+
+```css
+@property --fade-start {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+@property --fade-end {
+ syntax: "<length>";
+ inherits: false;
+ initial-value: 0px;
+}
+
+.scroller {
+ overflow-x: auto;
+ /* Example value: how far each fade reaches */
+ --fade-size: 3rem;
+ /* Gradient directions and positions are physical, so flip them for right-to-left content */
+ --fade-dir: right;
+ --fade-start-pos: 0;
+ --fade-end-pos: 100%;
+ mask:
+ linear-gradient(black, black) no-clip subtract,
+ linear-gradient(to var(--fade-dir), black, transparent) var(--fade-start-pos) 0 / var(--fade-start) 100% no-repeat no-clip,
+ linear-gradient(to var(--fade-dir), transparent, black) var(--fade-end-pos) 0 / var(--fade-end) 100% no-repeat no-clip;
+ animation: reveal-fade-start linear both, hide-fade-end linear both;
+ animation-timeline: scroll(self inline);
+ /* Each fade animates over the first or last --fade-size of scrolling */
+ animation-range: 0 var(--fade-size), calc(100% - var(--fade-size)) 100%;
+
+ &:dir(rtl) {
+ --fade-dir: left;
+ --fade-start-pos: 100%;
+ --fade-end-pos: 0;
+ }
+}
+
+@keyframes reveal-fade-start {
+ to {
+ --fade-start: var(--fade-size);
+ }
+}
+
+@keyframes hide-fade-end {
+ from {
+ --fade-end: var(--fade-size);
+ }
+}
+```
+
+- MANDATORY: Register `--fade-start` and `--fade-end` with `@property`. Unregistered custom properties do not interpolate, so the fades would jump.
+- Set `scroll-padding-inline` (or `scroll-padding-block`) to the fade size if the scroller uses scroll snapping or contains focusable items, so snapped and focused items never stop inside a fade.
+- For vertical scrollers, use `to bottom`, put the bands at `0 0` and `0 100%` with sizes `100% var(--fade-start)` and `100% var(--fade-end)`, and use `scroll(self block)` and `overflow-y`.
+- For right-to-left content, flip `--fade-dir` and swap the band positions, as in the `:dir(rtl)` rule above. The scroll timeline follows the writing direction, but gradient directions and mask positions are physical.
+
+### Strategy 2: overflow menu
+
+Hide the tabs that don’t fit and list them in a menu opened by a “More” button after the tablist.
+Build the button and its menu as a menu button; see `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`) for structure, positioning, and keyboard behavior.
+The rest of this section covers only what is specific to tabs.
+
+- **Place the “More” button outside the tablist.** A tablist may only contain tabs. This makes it a separate `Tab` stop that arrow keys do not reach. If arrow-key access matters more, move focus from the last visible tab to the “More” button on `ArrowRight`/`End`, and back on `ArrowLeft`. The tablist itself does nothing at its last tab, so this does not conflict with it, but it is custom key handling that users of the tab pattern may not expect.
+- **Make the “More” button look different from a tab.** Use an icon (such as a horizontal ellipsis) with an accessible name, not a text label: a text label looks like one more tab.
+- **Detect overflow with `IntersectionObserver`**, rooted at the tablist with `threshold: 1`, so partially visible tabs count as overflowed. It reports each tab as it starts or stops fitting, with no layout math.
+- **Hide overflowed tabs with `visibility: hidden`**, not `display: none` or `hidden`. They keep their layout box, so the observer still reports when they fit again, and they leave the focus order and the accessibility tree. Set `overflow: clip` on the tablist so they don’t overflow the page.
+- **Mirror each tab as a `menuitem`**. Show only the items whose tab is hidden. Activating an item selects its tab and focuses it. Focus the tab before hiding the popover: otherwise the popover returns focus to the previously focused tab, which selects it again.
+- **Hide the “More” button when no tab overflows.** This cannot loop: showing the button only narrows the tablist, so at least one tab still overflows.
+- **Keep the selected tab in the tablist.** DO NOT leave it in the menu or mark the “More” button as selected: it is a button, not a tab. When the selected tab overflows (selected from the menu, by find-in-page, or after a resize), set `display: none` on the tabs before it, closest first, until it fits. The observer then reports them as overflowed, so they appear in the menu. DO NOT reorder tabs (in the DOM or with CSS `order`): the removed tabs are gone from both the visual and the focus order, so the two still match. Keep overflowed tabs visible while they are selected or focused: a selected tab can then be focused before the observer catches up, and a focused tab keeps focus when a resize overflows it.
+
+```html
+<div class="tabs">
+ <div class="tablist" focusgroup="tablist nomemory" aria-label="Product details">
+ <button type="button">Overview</button>
+ <button type="button">Specifications</button>
+ <!-- … -->
+ </div>
+ <!-- Outside the tablist: a tablist may only contain tabs.
+ Icon, not text, so it does not read as another tab. -->
+ <button type="button" class="more" hidden aria-label="More tabs" aria-haspopup="menu" aria-expanded="false">⋯</button>
+ <!-- Menu: see the menu guide. One menuitem per tab. -->
+ <!-- Tab panels -->
+</div>
+```
+
+```js
+const observer = new IntersectionObserver(entries => {
+ for (const { target: tab, intersectionRatio } of entries) {
+ const overflowed = intersectionRatio < 1;
+ // CSS: .clipped:not([aria-selected="true"], :focus) { visibility: hidden; }
+ tab.classList.toggle('clipped', overflowed);
+ menuItemFor(tab).hidden = !overflowed;
+ }
+ more.hidden = !tabs.some(tab => tab.classList.contains('clipped'));
+ reveal();
+}, { root: tablist, threshold: 1 });
+
+tabs.forEach(tab => observer.observe(tab));
+
+// Also call after every selection change.
+// CSS: .displaced { display: none; }
+function reveal() {
+ const tab = tabs.find(tab => tab.ariaSelected === 'true');
+ const before = tabs.slice(0, tabs.indexOf(tab));
+ tabs.forEach(tab => tab.classList.remove('displaced'));
+ while (before.length && !fits(tab)) {
+ before.pop().classList.add('displaced');
+ }
+}
+
+// Checks both edges, so it works in either writing direction
+function fits(tab) {
+ const list = tablist.getBoundingClientRect();
+ const { left, right } = tab.getBoundingClientRect();
+ return left >= list.left && right <= list.right;
+}
+```
+
+### Strategy 3: Making inactive tabs smaller
+
+This may be combined with the overflow handling strategies described above to allow more tabs to fit before scrolling or showing a menu.
+It is more well suited to user-driven tablists (e.g. a document editor) rather than hardcoded UI tablists.
+
+- Let inactive tabs shrink and keep the selected tab at its full width: `flex: 0 1 auto` on the tabs, and `min-inline-size: max-content` on the selected tab, which also overrides any `max-inline-size`, so its label is never truncated. DO NOT use `flex-shrink: 0` for this: it cannot transition smoothly (see below).
+- Set a `min-inline-size` on the tabs. Once every inactive tab is at its minimum, the remaining overflow is handled by scrolling or the overflow menu.
+- Truncate shrunk labels with `text-overflow: ellipsis`. Put the label in its own element, so `overflow: hidden` applies to the text only and an icon beside it is never clipped.
+- Keep the full label in the DOM, so the accessible name and find-in-page are unaffected. Reveal it by scrolling the label inside the tab on hover, and on focus when activation is manual (with automatic activation the focused tab is selected, so it is already full width). See `single-line-overflow` (via `npx -y modern-web-guidance@latest retrieve "single-line-overflow"`) for more details.
+- If tabs have icons, keep the icon visible and truncate only the label, so a minimum-width tab is still recognizable.
+- Transition `min-inline-size` so tabs resize smoothly when the selection changes, instead of jumping. Set `interpolate-size: allow-keywords` on the tablist so it interpolates to and from `max-content`; no view transition is needed. Only transition it when `prefers-reduced-motion` is `no-preference`. Transitioning `flex-shrink` does not work: any value above 0 shrinks a tab all the way to its minimum when the tabs overflow.
+
+
+
+## Fallback strategies
+
+### Fallbacks & browser support for focusgroup
+
+Browser support for focusgroup: Limited availability.
+Supported by: Chrome 150 (Jun 2026) and Edge 150 (Jul 2026).
+Unsupported in: Firefox and Safari.
+
+Load `@microsoft/focusgroup-polyfill` only when native support is missing:
+
+```js
+if (!(Object.hasOwn(HTMLElement.prototype, 'focusGroup'))) {
+ const { polyfill } = await import('@microsoft/focusgroup-polyfill');
+ polyfill();
+}
+```
+
+- Use the `focusgroup` and `focusgroupstart` attributes, not the `focusGroup` property, which the polyfill does not add.
+- The polyfill does not notice items hidden or shown later: add `focusgroup="none"` to an item while it is hidden.
+
+### Fallbacks & browser support for `hidden=until-found`
+
+Browser support for hidden="until-found": Limited availability.
+Supported by: Chrome 102 (May 2022), Edge 102 (May 2022), and Firefox 148 (Feb 2026).
+Unsupported in: Safari.
+
+Treat `hidden=until-found` as an enhancement. Do not polyfill it: find-in-page cannot be reproduced across browsers.
+No feature detection is needed when setting it from script: in browsers without support, `panel.hidden = 'until-found'` sets the boolean `hidden`, so the panel is simply hidden and not searchable.
+
+### Fallbacks & browser support for `interpolate-size`
+
+Browser support for interpolate-size: Limited availability.
+Supported by: Chrome 129 (Sep 2024) and Edge 129 (Sep 2024).
+Unsupported in: Firefox and Safari.
+
+No fallback is needed: without `interpolate-size`, tabs resize instantly instead of transitioning.
+
+### Fallbacks & browser support for scroll-driven animations
+
+Baseline status for Scroll-driven animations: Newly available. It's been Baseline since 2026-10-27.
+Supported by: Chrome 115 (Jul 2023), Edge 115 (Jul 2023), Firefox 159 (Oct 2026), and Safari 26 (Sep 2025).
+
+Without scroll-driven animations, the fades are never shown, and neither are the shadows if scroll-state queries are also unsupported. Use one of these last-resort fallbacks.
+
+#### Shadows on a solid background: background attachment
+
+If the scroller has a solid background color, draw the shadows with backgrounds instead. This works in every browser and needs no JavaScript.
+Each shadow is a `scroll` background, which stays at the edge of the scrollport.
+Each shadow has a cover: a `local` background in the scroller's own color, which scrolls with the content.
+At either end of the content its cover sits on top of its shadow and hides it; once the user scrolls away from that end, the cover moves away and the shadow shows.
+
+```css
+@supports not ((container-type: scroll-state) or (animation-timeline: scroll())) {
+ .scroller {
+ background:
+ /* Covers: scroll with the content. Must use the scroller's own background color. */
+ linear-gradient(var(--surface) 30%, transparent) top / 100% 2.5rem no-repeat local,
+ linear-gradient(transparent, var(--surface) 70%) bottom / 100% 2.5rem no-repeat local,
+ /* Shadows: stay at the edges of the scrollport */
+ radial-gradient(farthest-side at 50% 0, rgb(0 0 0 / .15), transparent) top / 100% .75rem no-repeat,
+ radial-gradient(farthest-side at 50% 100%, rgb(0 0 0 / .15), transparent) bottom / 100% .75rem no-repeat,
+ var(--surface);
+ }
+}
+```
+
+The shadows paint behind the content, so content with its own opaque background hides them. In that case, use the `IntersectionObserver` fallback below.
+
+#### Fades, or shadows on any background: `IntersectionObserver`
+
+Use an `IntersectionObserver` to mark which edges have more content, and show the hints from those attributes. Observe the scroller's first and last children, with the scroller as the root and `threshold: 1`: a child that is not fully visible means there is more content beyond it.
+
+```js
+if (!CSS.supports('animation-timeline', 'scroll()')) {
+ for (const scroller of document.querySelectorAll('.scroller')) {
+ const [first, last] = [scroller.firstElementChild, scroller.lastElementChild];
+ // rootMargin: without it, sub-pixel widths can leave an edge child a fraction of a pixel short of fully visible
+ const observer = new IntersectionObserver(entries => {
+ for (const { target, intersectionRatio } of entries) {
+ scroller.classList.toggle(target === first ? 'more-start' : 'more-end', intersectionRatio < 1);
+ }
+ }, { root: scroller, threshold: 1, rootMargin: '1px' });
+
+ observer.observe(first);
+ observer.observe(last);
+ }
+}
+```
+
+```css
+/* Shadows */
+.scroller.more-start::before,
+.scroller.more-end::after {
+ opacity: 1;
+}
+
+/* Fades */
+.scroller {
+ transition: --fade-start .2s, --fade-end .2s;
+
+ &.more-start {
+ --fade-start: var(--fade-size);
+ }
+
+ &.more-end {
+ --fade-end: var(--fade-size);
+ }
+}
+```
+
+If a single child can be larger than the scroller (e.g. one long article), it is never fully visible, so this would always show both hints. Observe sentinels instead: empty elements that the script adds at each end of the scroller. A sentinel that is out of view means there is more content beyond it.
+
+```js
+// Must be valid children of the scroller (e.g. <li aria-hidden="true"> in a list)
+const [start, end] = [document.createElement('div'), document.createElement('div')];
+for (const sentinel of [start, end]) {
+ // A zero-size sentinel at the very edge never counts as intersecting
+ sentinel.style.cssText = 'min-inline-size: 1px; min-block-size: 1px';
+}
+scroller.prepend(start);
+scroller.append(end);
+// Observe them as above, with the default threshold, using !isIntersecting instead of intersectionRatio < 1
+```
diff --git a/skills/modern-web-guidance/guides/ui-components/toolbar.md b/skills/modern-web-guidance/guides/ui-components/toolbar.md
new file mode 100644
index 0000000..1c05b47
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/toolbar.md
@@ -0,0 +1,277 @@
+# Build a toolbar
+
+A toolbar groups related controls (formatting, alignment, view options) into one composite widget with a **single tab stop**. Users `Tab` into it once, move between controls with the arrow keys, and `Tab` out. Use it only for controls that act on something else (an editor, preview, canvas). For site navigation, see `navbar` (via `npx -y modern-web-guidance@latest retrieve "navbar"`); for a dropdown or context menu of commands without a persistent row of controls, see `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`).
+
+## Structure and semantics
+
+MANDATORY: Put `role="toolbar"` and an `aria-label` on the container. Wrap related controls in `role="group"` with their own `aria-label`, and divide groups with `role="separator"` and `aria-orientation="vertical"`. If a wrapped separator would sit alone at a row end, hide it visually with `opacity: 0`, not `display: none` or `visibility: hidden`, which also remove it from the accessibility tree. Optionally add `aria-controls` pointing at the element the toolbar acts on; it is only worth adding when the toolbar controls one specific element.
+
+* Use real `<button type="button">` elements.
+* Icon-only buttons need an `aria-label`; tooltips do not replace it. Render decorative icons with `<svg aria-hidden="true">` and `currentColor`, or with a CSS `mask`, `background-color: currentColor`, and `forced-color-adjust: none` so forced-colors mode does not strip the fill. For a reusable CSS icon token system, see `icons` (via `npx -y modern-web-guidance@latest retrieve "icons"`).
+* Toggle buttons (bold, italic) use `aria-pressed="true|false"`. Do not change their label when toggled.
+* A mutually exclusive set (left/center/right) uses `aria-pressed` on each button, with script keeping exactly one `true`.
+* Action buttons (copy, undo, save) run once and have no on/off state, so DO NOT add `aria-pressed` to them. Mark `aria-pressed` only on buttons that stay on or off.
+* Disable with `aria-disabled="true"` rather than `disabled` so the control stays focusable and reachable by arrow keys. Ignore clicks while it is set.
+
+```html
+<div role="toolbar" focusgroup="toolbar wrap" aria-label="Text formatting" aria-controls="preview">
+ <div role="group" aria-label="Style">
+ <button type="button" aria-pressed="false" aria-label="Bold" title="Bold"></button>
+ </div>
+ <span role="separator" aria-orientation="vertical"></span>
+ <!-- Overflow trigger: the last item in the toolbar -->
+ <button type="button" aria-label="More actions" aria-haspopup="menu" aria-expanded="false"
+ popovertarget="more-menu" title="More actions"></button>
+</div>
+```
+
+## Action buttons and feedback
+
+Toggles show their result through `aria-pressed`. An action has no state to show, so a screen reader user gets no confirmation unless you provide it. When the result is not otherwise visible or announced (copy, save), write a short message to a live region outside the toolbar. If the action changes content that is already announced or focused, skip the message.
+
+```html
+<!-- Always present in the DOM so the announcement is reliable; keep it outside the toolbar -->
+<p role="status"></p>
+```
+
+```js
+// Report the outcome, including failure; clipboard access can be denied
+try {
+ await navigator.clipboard.writeText(text);
+ status.textContent = "Text copied";
+} catch {
+ status.textContent = "Copy failed";
+}
+```
+
+## Keyboard navigation
+
+MANDATORY: Only one item is in the tab order at a time. Put `focusgroup="toolbar wrap"` on the `role="toolbar"` container: the browser provides the roving tab stop, arrow-key movement across all groups (wrapping at the ends, reversed in RTL), `Home`/`End`, and focus restoration after a click. Do not add a second roving-tabindex system alongside it. Where `focusgroup` is unsupported, install the fallback in "Fallbacks" below.
+
+## Vertical toolbar
+
+Choose a vertical toolbar when controls stack along a side edge (a tool palette or zoom controls beside a canvas); otherwise use a horizontal one. Everything above applies except:
+
+* Set `aria-orientation="vertical"` on the toolbar and use `focusgroup="toolbar wrap block"` so `ArrowDown`/`ArrowUp` move between items.
+* Lay items out in a column (`flex-direction: column`, no wrapping).
+* A separator between stacked items is horizontal: use `aria-orientation="horizontal"` (the separator default) there, not `vertical`.
+* Tooltips open beside the button (`position-area: inline-end`), not below it; see Tooltips below.
+
+## Visible states
+
+* Size each button at least 24×24 CSS px using `min-inline-size`/`min-block-size` (not `inline-size`/`block-size`), so content can grow the target but never shrink it. Enlarge it under `@media (pointer: coarse)`. Values like `2.5rem` and `3rem` are examples.
+
+* Keep a clear `:focus-visible` outline with an offset; never remove it.
+* Style toggled state from the ARIA attribute (`[aria-pressed="true"]`), not a separate class, so visual and accessible state cannot diverge.
+* Show the toggled state by changing the button background; if the contrast between the button background and the adjacent background color is less than 3:1 in each supported color scheme, provide an additional visual cue such as an outline or inset shadow around the background that meets the 3:1 threshold. For more information, see `color` (via `npx -y modern-web-guidance@latest retrieve "color"`).
+* Under `forced-colors: active`, use system colors (`ButtonText`, `Highlight`).
+* Draw separators and tooltip boxes with a border (a `transparent` one is fine), not `background` alone, which forced colors replaces with the page color.
+* Wrap hover styles in `@media (hover: hover)` and transitions in `@media (prefers-reduced-motion: no-preference)`.
+
+## Tooltips for icon-only buttons
+
+Give each icon-only button a `title` as the baseline tooltip. Only where both interest invokers and anchor positioning are supported, upgrade it to an interest invoker with `popover="hint"`, which shows the tooltip without closing an open menu popover. Elsewhere the native `title` tooltip stays.
+
+MANDATORY: Position the hint on the axis the toolbar does not stack along: `position-area: block-end` (fallback `flip-block`) for a horizontal toolbar, `position-area: inline-end` (fallback `flip-inline`) for a vertical one. A hint placed along the stacking axis covers the next control and swallows its click, because the hint stays open while the pointer is over it.
+
+```html
+<button type="button" aria-label="Bold" title="Bold">…</button>
+```
+
+```js
+// Upgrade title tooltips only when interest invokers and anchor positioning both work
+if ("interestForElement" in HTMLButtonElement.prototype && CSS.supports("position-area", "block-end")) {
+ document.querySelectorAll('[role="toolbar"] button[title]').forEach((b, i) => {
+ const tip = Object.assign(document.createElement("div"), { id: `tip-${i}`, textContent: b.title });
+ tip.popover = "hint";
+ b.setAttribute("interestfor", tip.id);
+ b.removeAttribute("title"); // avoid a second, native tooltip
+ document.body.append(tip); // keep open hint nodes out of role="group" / role="toolbar"
+ });
+}
+```
+
+`interestfor` is specified to wire hint popovers (`popover="hint"`) for assistive technology itself, based on what the target contains. A **plain hint** (text and images only) becomes the trigger's accessible description, or its name if it has none. A **rich hint** (headings, links, or other interactive content) gets a minimum role of `tooltip`, the trigger gets `aria-expanded` and an `aria-details` relation while the hint is open, and the open hint comes right after the trigger in the tab order so keyboard users can reach its content.
+
+Browsers and screen readers do not yet expose this consistently, so add explicit ARIA as well:
+
+- **Hint that repeats the trigger's accessible name** (e.g. an icon-only button with `aria-label="Bold"` and a "Bold" tooltip): add nothing. A description identical to the name would be read twice.
+- **Hint on a trigger with no visible label of its own** (e.g. an icon-only button without `aria-label`): `aria-labelledby` on the trigger pointing at the hint, so the hint becomes the name.
+- **Hint whose trigger also opens it on activation** (a toggletip, or any button whose only job is the hint: give it `popovertarget` with `popovertargetaction="show"`): `role="tooltip"` on the hint and `aria-expanded` on the trigger, kept in sync with the popover's `toggle` event. A description read right after "button" suggests further actions and muddles the role; the expanded state tells the user there is content to reveal and whether it is open, and pressing the button delivers it. Place the hint right after the trigger in the DOM so reading keys reach its content once it is open.
+- **Hint whose trigger does something else on activation** (a link, a button with its own action): `role="tooltip"` on the hint and `aria-describedby` on the trigger, never `aria-expanded`. A trigger announced as "collapsed" suggests `Enter` would expand it, but `Enter` navigates or acts. The hint must be something the user can afford to miss: a hovercard previews the destination, a tooltip on an action button describes the action.
+- **DO NOT** attach a hint that opens on activation to a control that already uses `aria-expanded` for something else (for example, a menu button). Give that hint its own trigger instead.
+- **DO NOT** move focus into the target when interest is shown (no `autofocus`, no `focus()` in an `interest` listener). Interest is triggered by hover or focus alone, so moving focus would fail WCAG 3.2.1 (On Focus).
+
+Not every screen reader reads descriptions when moving through the page (NVDA skips them in browse mode by design), so a hint exposed as a description must only carry content the user can afford to miss. Link previews and tooltips on action controls qualify; anything the user needs belongs in a toggletip or inline.
+
+Wire this with a short script instead of hand-authoring the attributes, so the markup stays declarative and the same rules apply to every hint. The script should:
+
+1. Run in every browser, before loading the `interestfor` polyfill, once the DOM is parsed, and expose a function that can be called again for content inserted later. Scanning upfront is required: a browse-mode screen reader user needs the attributes in place before any interaction, so wiring them lazily on `focus` or `interest` is too late, and so is waiting for the polyfill, which wires its ARIA only on `load` and adds no `role="tooltip"` to plain hints.
+2. For every `[interestfor]` trigger whose target has `popover="hint"`, normalize whitespace and compare the hint text with the trigger's accessible name (`aria-labelledby` targets, else `aria-label`, else text content including image `alt`, else `title`). Equal: do nothing. Otherwise set `role="tooltip"` on the hint if it has no role.
+3. When the trigger has no name, point `aria-labelledby` at the hint unless it already has one. Otherwise, if the trigger also opens the hint on activation (a `popovertarget` or `commandfor` naming the hint), set `aria-expanded` to the popover's current state (`:popover-open`) unless it already has `aria-expanded`, and remember which triggers the script owns; if not, point `aria-describedby` at the hint unless it already has one.
+4. Keep `aria-expanded` in sync from the popover's `toggle` event in every browser with a single capturing listener on `document`, updating every trigger with a matching `interestfor` that the script owns (the `interestfor` polyfill does not sync `aria-expanded` on plain-text hints or when a toggletip is opened via `popovertarget`).
+
+Things that are easy to get wrong:
+
+- `toggle` does not bubble. A bubbling listener on `document` never fires; use the capture phase (or a listener per popover).
+- Sync `aria-expanded` from `toggle`, not from `interest`/`loseinterest`. The popover is the source of truth: it can be closed by `Escape`, light dismiss, or another invoker, and several triggers can share one hint.
+- A hidden popover is a valid `aria-describedby` or `aria-labelledby` target. Do not force the hint open or duplicate its text to make it "visible".
+- Do not add `aria-haspopup` or a live region to any hint.
+- Do not override author ARIA: an existing `aria-describedby`, `aria-labelledby`, or `aria-expanded` on the trigger wins.
+
+By default, interest is shown and lost for keyboard and mouse users with a delay of half a second. This prevents the targeted popover from opening while tabbing through a page or moving your mouse around, and from closing while moving your mouse from the trigger to the popover. To adjust the timing, use the `interest-delay` CSS property.
+
+```css
+[interestfor]{
+ /* Shorthand for interest-delay-start and interest-delay-end */
+ interest-delay: 0.2s 0.1s;
+}
+```
+
+If users are likely to move through multiple triggers in quick succession, set the initial delay to `0s` if an interest-triggered popover is already open.
+
+```css
+:root:has(:interest-source) [interestfor] {
+ interest-delay-start: 0s;
+}
+```
+
+```css
+[popover="hint"] {
+ inset: auto;
+ /* Anchor to the invoker; flip to the other side if there is no room */
+ position-area: block-end;
+ position-try-fallbacks: flip-block;
+}
+```
+
+## Overflow menu for secondary actions (optional)
+
+Two patterns fit a toolbar into a narrow space: an overflow menu, better on desktop, or a horizontally scrollable toolbar with no scrollbar and scroll hints, better on mobile. For the scrollable pattern use `overflow-x: auto; scrollbar-width: none; scroll-snap-type: x proximity`, and hint at hidden controls with edge fades (`mask-image`) or a partly visible last item. Choose by input type (`@media (pointer: coarse)`) or container width.
+
+Add a trailing "More actions" menu when the toolbar has secondary actions or must fit narrow containers; skip it if every control is common and fits. If items must move into the menu dynamically as space runs out, build that overflow behavior yourself.
+
+* Make the trigger the last toolbar item (`aria-label="More actions"`, `aria-haspopup="menu"`, `aria-expanded="false"`, and `popovertarget` pointing at the menu popover) with the conventional three vertical dots icon (`⋮`). Open it only on activation—never preview on focus when arrowing across the toolbar.
+* Anchor the `popover` container to its trigger (`inset: auto; position-area: block-end span-inline-start; position-try-fallbacks: flip-block, flip-inline`) and nest `<div focusgroup="menu nomemory" aria-label="More actions">` inside it, adding `role="menu"`, `role="menuitem"`, `tabindex="-1"`, and `ArrowDown`/`ArrowUp`/`Home`/`End` only when `'focusGroup' in HTMLElement.prototype` is false. Sync `aria-expanded` and focus the first item on `toggle`, close the popover on `Tab` without trapping focus, and let `Space` on `role="menuitemcheckbox"` toggle `aria-checked` without closing. For nested submenus or radio groups, see `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`).
+* Announce the result of every menu activation in the toolbar's live region, such as `"Strikethrough on"` or `"Formatting cleared"`. When closing the menu returns focus to the trigger, delay the live-region write slightly—for example `500ms`—so the focus-change announcement does not preempt it.
+
+## Fallback strategies
+
+### Fallbacks & browser support for `focusgroup`
+
+Browser support for focusgroup: Limited availability.
+Supported by: Chrome 150 (Jun 2026) and Edge 150 (Jul 2026).
+Unsupported in: Firefox and Safari.
+
+Keep `focusgroup` in the markup. Only if `'focusGroup' in HTMLElement.prototype` is false, load a roving-tabindex fallback; never install it when native focusgroup is present. The fallback implements what focusgroup does natively:
+
+* The active item has `tabindex="0"`; all others have `tabindex="-1"`. Initially the first item is active.
+* On `focusin`, move `tabindex="0"` to the focused item so returning to the toolbar (including after a click) restores position.
+* In a horizontal toolbar, `ArrowRight`/`ArrowLeft` move to the next/previous item across all groups and wrap at the ends. In RTL, reverse the directions. Do not wire `ArrowUp`/`ArrowDown`.
+* In a vertical toolbar, `ArrowDown`/`ArrowUp` move to the next/previous item instead, and `ArrowLeft`/`ArrowRight` do nothing.
+* `Home`/`End` move to the first/last item.
+* Call `preventDefault()` only for keys the toolbar handles so `Tab` keeps working.
+
+```js
+if (!('focusGroup' in HTMLElement.prototype)) {
+ // items = every toolbar control across all groups, in DOM order
+ items.forEach((b, i) => (b.tabIndex = i ? -1 : 0));
+ bar.addEventListener("focusin", ({ target }) => {
+ if (items.includes(target)) items.forEach((b) => (b.tabIndex = b === target ? 0 : -1));
+ });
+ // Read direction and orientation at event time so runtime changes are honored
+ const vertical = bar.getAttribute("aria-orientation") === "vertical";
+ // Only horizontal toolbars flip with direction: RTL does not flip Up/Down
+ const rtl = getComputedStyle(bar).direction === "rtl";
+ const steps = vertical
+ ? { ArrowDown: 1, ArrowUp: -1 }
+ : { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 };
+ // keydown: look up steps[key] (or Home/End), move focus, preventDefault only for handled keys
+}
+```
+
+### Fallbacks & browser support for Interest invokers
+
+Browser support for Interest invokers: Limited availability.
+Supported by: Chrome 149 (Jun 2026) and Edge 149 (Jun 2026).
+Unsupported in: Firefox and Safari.
+
+Do not load an `interestfor` polyfill here: when native interest invokers or anchor positioning are missing, the upgrade script is skipped and buttons keep their baseline `title` tooltip.
+
+### Fallbacks & browser support for Popover
+
+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
+Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
+
+The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
+
+**Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
+ import("@oddbird/popover-polyfill");
+}
+```
+
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Fallbacks & browser support for `popover="hint"`
+
+Browser support for popover="hint": Limited availability.
+Supported by: Chrome 151 (Jul 2026), Edge 151 (Jul 2026), and Firefox 153 (Jul 2026).
+Unsupported in: Safari.
+
+The popover polyfill does not add `popover="hint"`. Where `popover` exists without `hint`, two tooltips can stay open at once (for example one opened by focus and one by hover). Treat this as graceful degradation: the upgrade only runs where interest invokers are supported, and other browsers keep the native `title` tooltip.
+
+### Fallbacks & browser support for Clipboard API
+
+Baseline status for the api.Clipboard.writeText capability: Widely available. It's been Baseline since 2020-03-24.
+Supported by: Chrome 66 (Apr 2018), Edge 79 (Jan 2020), Firefox 63 (Oct 2018), Safari 13.1 (Mar 2020), and Safari iOS 13.4 (Mar 2020).
+
+Where the Clipboard API is unavailable, `navigator.clipboard` is undefined and the call throws, so the `catch` branch in the feedback snippet reports the failure.
+
+### Fallbacks & browser support for Anchor positioning
+
+Browser support for Anchor positioning: Limited availability.
+Supported by: Safari 27 (Sep 2026).
+Unsupported in: Chrome, Edge, and Firefox.
+
+Without anchor positioning, a popover is placed by the UA at the center of the viewport. Tooltips need no fallback: the `title` upgrade above is skipped without anchor positioning. For the overflow menu, position it from script so it stays attached to its trigger. Keep the CSS inside `@supports not (position-area: block-end)` so supporting browsers are unaffected.
+
+```css
+@supports not (position-area: block-end) {
+ #more-menu {
+ /* Viewport coordinates are set from script when the menu opens */
+ position: fixed;
+ inset: auto;
+ margin: 0;
+ }
+}
+```
+
+```js
+// Only needed without anchor positioning; place the menu below its trigger
+// and flip above it when it would overflow the viewport.
+menu.addEventListener("toggle", ({ newState }) => {
+ if (newState !== "open" || CSS.supports("position-area", "block-end")) return;
+ const t = more.getBoundingClientRect();
+ const m = menu.getBoundingClientRect();
+ const below = t.bottom + m.height <= innerHeight;
+ menu.style.top = `${below ? t.bottom : t.top - m.height}px`;
+ // Right-align with the trigger, clamped to the viewport
+ menu.style.left = `${Math.max(0, Math.min(t.right - m.width, innerWidth - m.width))}px`;
+});
+```
diff --git a/skills/modern-web-guidance/guides/user-experience/content-first-noise-reduction.md b/skills/modern-web-guidance/guides/user-experience/content-first-noise-reduction.md
index ef13d0f..ff61899 100644
--- a/skills/modern-web-guidance/guides/user-experience/content-first-noise-reduction.md
+++ b/skills/modern-web-guidance/guides/user-experience/content-first-noise-reduction.md
@@ -81,7 +81,7 @@ Put long or rarely needed content (specs, FAQs, fine print) in a `details` eleme
### Scroll-state queries
Browser support for Container scroll-state queries: Limited availability.
-Supported by: Chrome 133 (Feb 2025) and Edge 133 (Feb 2025).
+Supported by: Chrome 144 (Jan 2026) and Edge 144 (Jan 2026).
Unsupported in: Firefox and Safari.
Without scroll-state queries, the bar never hides, but it stays compact and usable. If your Baseline target includes those browsers, add a small script so the bar hides there too. Browsers that support other scroll-state queries but not `scrolled` also keep the bar visible.
@@ -122,22 +122,16 @@ With a bundler or import map:
```js
// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
-if (!("popover" in HTMLElement.prototype)) {
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
import("@oddbird/popover-polyfill");
}
```
-Without a bundler, import from a CDN inside a `<script type="module">`:
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
-```html
-<script type="module">
- if (!("popover" in HTMLElement.prototype)) {
- import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
- }
-</script>
-```
-
-**Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
```css
[popover]:is(:popover-open, .\:popover-open) {
@@ -145,8 +139,6 @@ Without a bundler, import from a CDN inside a `<script type="module">`:
}
```
-Alternatively, for a legacy fallback without a polyfill, use `position: fixed` and manually calculate coordinates via `getBoundingClientRect()` or rely on default positioning with `inset: auto` if that's acceptable for the use case.
-
### Invoker commands
Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.
diff --git a/skills/modern-web-guidance/guides/user-experience/form-factor-adaptation.md b/skills/modern-web-guidance/guides/user-experience/form-factor-adaptation.md
new file mode 100644
index 0000000..f93beb7
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/form-factor-adaptation.md
@@ -0,0 +1,108 @@
+# Adapt to the form factor
+
+The same interface runs on phones, laptops, and foldables, with touch, mouse, or keyboard. Size controls for the input, let components adapt to their container, and keep text and controls clear of system UI.
+
+For page-level responsive techniques (dynamic viewport units, aspect ratios, and fluid type), see `responsive-design` (via `npx -y modern-web-guidance@latest retrieve "responsive-design"`).
+
+## Implementation
+
+### Size targets for the input method
+
+Make every control at least 24×24 CSS pixels (WCAG 2.5.8), and at least 44×44 on touch screens (WCAG 2.5.5). Links inside sentences are exempt. For checkboxes and radios, wrap the input in its `<label>` and size the label. To keep small icons visually compact, extend their hit area with a pseudo-element. Leave enough space around controls so extended hit areas do not overlap each other or reach past the edge of the screen.
+
+```css
+:root { --target-size: 24px; }
+@media (pointer: coarse) {
+ :root { --target-size: 44px; }
+}
+:where(button, select, textarea, input:not([type="checkbox"], [type="radio"]), [role="button"], nav a, label:has(input[type="checkbox"], input[type="radio"])) {
+ min-block-size: var(--target-size);
+ min-inline-size: var(--target-size);
+}
+:where([role="button"], nav a, label:has(input[type="checkbox"], input[type="radio"])) { display: inline-flex; align-items: center; }
+.icon-button { position: relative; }
+.icon-button::after {
+ content: "";
+ position: absolute;
+ inset: -10px;
+}
+```
+
+### Let components respond to their container
+
+Use container queries instead of viewport-width media queries for component layout, so a component adapts wherever it is placed. Keep media queries for what a container can't know: the input device (such as `pointer: coarse` for touch screens) and user settings (such as `prefers-color-scheme`).
+
+```css
+.product-list {
+ /* Name containers so queries inside nested containers target the right ancestor. */
+ container: products / inline-size;
+}
+/* A container query styles the container's descendants, never the container itself. */
+@container products (inline-size > 40rem) {
+ .product-card { display: grid; grid-template-columns: 10rem 1fr; }
+}
+```
+
+DO NOT query `height` or `block-size` on an `inline-size` container: it measures only width. Use `container-type: size` only on a container with a definite height.
+
+- For more container query patterns, such as card layouts, see `size-aware-styling` (via `npx -y modern-web-guidance@latest retrieve "size-aware-styling"`).
+- To change a component's layout based on what child elements it contains (for example, switching a card to a side-by-side layout when it includes an image), see `content-based-styling` (via `npx -y modern-web-guidance@latest retrieve "content-based-styling"`).
+
+### Keep UI clear of notches and system bars
+
+When drawing edge to edge with `<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">`, pad fixed and edge-anchored UI by the safe-area insets.
+
+```css
+.bottom-bar {
+ position: fixed;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ padding-bottom: max(0.75rem, env(safe-area-inset-bottom, 0px));
+ padding-left: max(0.75rem, env(safe-area-inset-left, 0px));
+ padding-right: max(0.75rem, env(safe-area-inset-right, 0px));
+}
+```
+
+Pad UI anchored to the top edge the same way with `safe-area-inset-top`.
+
+### Balance headings and prettify body text
+
+Apply `text-wrap: balance` to short headings (`h1, h2, h3`) and `text-wrap: pretty` to body text (`p, li`) to prevent typographic orphans. For full text-wrapping rules, see `improve-text-layout-and-legibility` (via `npx -y modern-web-guidance@latest retrieve "improve-text-layout-and-legibility"`). DO NOT apply either property to `*`: both incur layout overhead, and `balance` only helps short blocks of text.
+
+### Label icon-only buttons
+
+Give every icon-only button an accessible name using `aria-label`, an `<img alt>`, or visually hidden text, and hide decorative icons with `aria-hidden="true"`. For more accessible naming patterns, see `accessibility` (via `npx -y modern-web-guidance@latest retrieve "accessibility"`).
+
+### Keep content inside its box
+
+Ensure text and controls are never clipped, squished to zero dimensions, or overflowing at any viewport width down to 320 CSS pixels (WCAG 1.4.10).
+
+```css
+/* Media never overflows its column. */
+img, video { max-inline-size: 100%; block-size: auto; }
+/* Long words and URLs wrap instead of widening the page. */
+body { overflow-wrap: anywhere; }
+/* Flex and grid items don't shrink below their content by default. Let non-control items shrink so controls keep their minimum size. */
+:where(.toolbar > :not(button, input, select, textarea, a, [role="button"], label)) { min-inline-size: 0; }
+.toolbar { display: flex; }
+/* The target-size minimum lets controls in a crowded row shrink below their text, so let nav bars and toolbars that are already rows wrap. */
+:where(nav, nav ul, .toolbar) { flex-wrap: wrap; }
+```
+
+- Use `min-block-size` instead of a fixed `height` on anything that contains text.
+- DO NOT truncate headings with `text-overflow: ellipsis`, and do not clip controls with `overflow: hidden` on their parents.
+- To allow text and layouts to scale with operating system accessibility settings, see `respect-os-text-scale` (via `npx -y modern-web-guidance@latest retrieve "respect-os-text-scale"`). To size form controls dynamically as users type, see `form-fields-automatically-fit-contents` (via `npx -y modern-web-guidance@latest retrieve "form-fields-automatically-fit-contents"`).
+
+## Fallback strategies
+
+### Text wrapping
+
+Baseline status for text-wrap: balance: Newly available. It's been Baseline since 2024-05-13.
+Supported by: Chrome 114 (May 2023), Edge 114 (Jun 2023), Firefox 121 (Dec 2023), and Safari 17.5 (May 2024).
+
+Browser support for text-wrap: pretty: Limited availability.
+Supported by: Chrome 117 (Sep 2023), Edge 117 (Sep 2023), and Safari 26 (Sep 2025).
+Unsupported in: Firefox.
+
+Browsers without support ignore `text-wrap: balance` and `text-wrap: pretty` and wrap text normally. No fallback is needed.
diff --git a/skills/modern-web-guidance/guides/user-experience/natural-interactions.md b/skills/modern-web-guidance/guides/user-experience/natural-interactions.md
new file mode 100644
index 0000000..805da89
--- /dev/null
+++ b/skills/modern-web-guidance/guides/user-experience/natural-interactions.md
@@ -0,0 +1,155 @@
+# Implement natural interactions
+
+Interfaces feel natural when every input gets an immediate response, motion behaves like a physical object, content follows the user's finger, and nothing depends on a mouse.
+
+## Implementation
+
+### Give every control hover, press, and focus feedback
+
+```css
+:where(button) {
+ /* example durations */
+ transition: box-shadow 150ms ease-out, scale 150ms ease-out;
+}
+button:hover { box-shadow: 0 2px 8px rgb(0 0 0 / 0.2); }
+a:hover { text-decoration-thickness: 2px; }
+button:active { scale: 0.97; } /* example value */
+
+:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
+ outline: 2px solid CanvasText;
+ outline-offset: 3px;
+}
+```
+
+- Use `:focus-visible` so keyboard users always see a clear focus ring, without showing it on mouse clicks.
+- DO NOT remove focus outlines (`outline: none` or `outline: 0`) without providing an equally visible replacement with at least a 3:1 contrast ratio against the page (WCAG 1.4.11). `CanvasText` is the text color for the page's `color-scheme`, so it contrasts with the default page background in light mode, in dark mode (with `color-scheme: light dark`), and in forced colors. If you set your own page background, pick a ring color with 3:1 against it. `currentColor` fails when a button's text color matches the page.
+- Make each interaction state look different, including combinations: hover, press, pressing while hovering, and keyboard focus. In the example, hover adds a shadow, press a scale, and focus an outline, so any combination shows each of its parts.
+
+### Open disclosures from their trigger
+
+Popovers and dropdowns should visibly open from the control that triggered them: scale out from the corner touching the trigger, or slide out from its side. Menus and hovercards have their own open motion; follow `menu` (via `npx -y modern-web-guidance@latest retrieve "menu"`) and `hovercard` (via `npx -y modern-web-guidance@latest retrieve "hovercard"`). For other popovers, place the popover next to its trigger and align `transform-origin` with the corner that touches it. To flip dropdowns at viewport edges, see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`).
+
+```css
+.dropdown {
+ /* popovertarget makes the trigger the popover's anchor. */
+ position-area: bottom span-right;
+ inset: auto;
+ margin: 0;
+ /* The corner touching the trigger; change it whenever the placement changes. */
+ transform-origin: top left;
+}
+/* example durations */
+.dropdown:is(:popover-open, .\:popover-open) { animation: fade-in 150ms ease-out both; }
+@media (prefers-reduced-motion: no-preference) {
+ .dropdown:is(:popover-open, .\:popover-open) {
+ /* optional example spring curve, written inline */
+ animation: grow 300ms linear(0, 0.45 15%, 1.08 35%, 0.97 55%, 1.01 75%, 1) both, fade-in 150ms ease-out both;
+ }
+}
+@keyframes grow { from { scale: 0.9; } }
+@keyframes fade-in { from { opacity: 0; } }
+```
+
+- Keep animations on the compositor (`transform`, its individual properties, and `opacity`) and respect reduced-motion preferences; see `motion` (via `npx -y modern-web-guidance@latest retrieve "motion"`). This example animates the opening only; for exit transitions, see `animate-to-from-top-layer` (via `npx -y modern-web-guidance@latest retrieve "animate-to-from-top-layer"`).
+- Trigger popovers declaratively using `<button popovertarget="dropdown-id">` (see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`)) to get native click, keyboard, and dismiss behavior without JavaScript.
+- For a springy open, use a `linear()` curve that overshoots slightly before settling (an output value above 1); see `physics-based-easing` (via `npx -y modern-web-guidance@latest retrieve "physics-based-easing"`).
+
+### Make horizontal scrollers swipeable
+
+Any horizontally scrollable row of items, such as a carousel, gallery, or row of chips, should scroll natively and snap to its items.
+
+```css
+.scroller {
+ display: flex;
+ gap: 1rem;
+ overflow-x: auto;
+ scroll-snap-type: x mandatory;
+}
+.scroller > * {
+ flex: 0 0 85%; /* example item width */
+ scroll-snap-align: start;
+}
+```
+
+- Native overflow scrolling gives swiping its physics and momentum, and snapping makes each swipe come to rest on an item, with no touch listeners.
+- If none of the scroller's items contains a link, button, or other focusable element, make the scroller itself focusable and labeled (`<div class="scroller" role="region" aria-label="Featured items" tabindex="0">`), so keyboard users can reach it and scroll it with the arrow keys. When items are focusable, tabbing to them already scrolls them into view.
+- To highlight the item that snaps into place, see `carousel-snap-highlights` (via `npx -y modern-web-guidance@latest retrieve "carousel-snap-highlights"`). To swipe a list item aside to reveal actions, see `swipe-to-reveal` (via `npx -y modern-web-guidance@latest retrieve "swipe-to-reveal"`). For side menus that close when swiped away, see `navigation-drawer` (via `npx -y modern-web-guidance@latest retrieve "navigation-drawer"`).
+- For carousel controls such as previous and next buttons and scroll markers, see `carousel` (via `npx -y modern-web-guidance@latest retrieve "carousel"`).
+
+### Add motion blur to large, fast movements (optional)
+
+For large, rapid translations (such as a full-screen sheet sliding into view), a subtle, temporary blur softens the movement. `filter` doesn't run only on the compositor, so keep blur to large, brief movements, skip it for small controls or slow transitions, and always guard it with a reduced-motion media query.
+
+```css
+@media (prefers-reduced-motion: no-preference) {
+ .sheet.is-open { animation: sheet-in 300ms ease-out both; } /* example duration */
+}
+@keyframes sheet-in {
+ from { translate: 0 100%; filter: blur(6px); } /* example blur radius */
+}
+```
+
+### Make every action reachable without a mouse
+
+- Use `<button>` for actions and `<a>` with an `href` for navigation. Both receive keyboard focus and activate on <kbd>Enter</kbd>; buttons also activate on <kbd>Space</kbd>.
+- Menus and dropdowns may open on hover, but never only on hover: they also open on click, tap, and keyboard activation, stay open while the pointer moves onto them, and close with <kbd>Esc</kbd> (WCAG 2.1.1, 1.4.13).
+- Controls or details revealed in place on hover, such as card actions, must also appear on keyboard focus and be visible by default on devices without hover:
+
+```css
+.card .actions {
+ opacity: 0;
+
+ .card:hover &,
+ .card:focus-within & { opacity: 1; }
+
+ @media (hover: none) { opacity: 1; }
+}
+```
+
+For tooltips and previews triggered on hover, focus, or long-press, see `interest-triggered-tooltips` (via `npx -y modern-web-guidance@latest retrieve "interest-triggered-tooltips"`) and `interest-triggered-action-previews` (via `npx -y modern-web-guidance@latest retrieve "interest-triggered-action-previews"`).
+
+## Fallback strategies
+
+### Fallbacks & browser support for Popover
+
+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.
+Supported by: Chrome 116 (Aug 2023), Edge 116 (Aug 2023), Firefox 125 (Apr 2024), Safari 17 (Sep 2023), and Safari iOS 18.3 (Jan 2025).
+
+The Popover API is mostly **progressive enhancement**, but its defining behaviors — top-layer promotion, light-dismiss, and `popovertarget` invocation — have no CSS-only equivalent. Older browsers need a polyfill, or a manual fallback if you would rather not ship one.
+
+**Polyfill:** To support the `popover` attribute in older browsers, conditionally load [`@oddbird/popover-polyfill`](https://github.com/oddbird/popover-polyfill). **MANDATORY:** Feature detect by checking for the `popover` property on `HTMLElement.prototype`, and load the polyfill **only** when native support is missing — do NOT load it unconditionally.
+
+With a bundler or import map:
+
+```js
+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
+if (!Object.hasOwn(HTMLElement.prototype, "popover")) {
+ import("@oddbird/popover-polyfill");
+}
+```
+
+If not using a package manager, import from a CDN, e.g. `"https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js"`.
+
+Caveats when using the polyfill:
+- Do NOT use the `popover` IDL attribute for any code that may run before the polyfill is fully loaded. It will not be mirrored as an attribute, the popover will not be picked up by the polyfill, and the property will be shadowing the accessor the polyfill adds forever. Use `setAttribute()`/`removeAttribute()` instead.
+- **Styling caveat:** The polyfill cannot define the real `:popover-open` pseudo-class, so it applies a `.\:popover-open` class instead. **MANDATORY:** Combine the two with `:is()` or `:where()`, otherwise browsers that lack `:popover-open` discard the entire rule:
+
+```css
+[popover]:is(:popover-open, .\:popover-open) {
+ display: block;
+}
+```
+
+### Anchor positioning
+
+Baseline status for the html.elements.button.popovertarget.implicit_anchor_reference capability: Newly available. It's been Baseline since 2026-01-13.
+Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 147 (Jan 2026), and Safari 26 (Sep 2025).
+
+Without support, `inset: auto` leaves the popover at the top-left corner of the viewport. When `CSS.supports('position-area: bottom')` is false, set the popover's `top` and `left` from the trigger's `getBoundingClientRect()` in a `beforetoggle` event listener.
+
+### Linear easing
+
+Baseline status for linear() easing: Widely available. It's been Baseline since 2023-12-11.
+Supported by: Chrome 113 (May 2023), Edge 113 (May 2023), Firefox 112 (Apr 2023), and Safari 17.2 (Dec 2023).
+
+Browsers without `linear()` drop the declaration that uses it, so precede it with one that uses a keyword such as `ease-out`, as the fade-in above does. Write `linear()` inline, not through a custom property, or the earlier declaration is discarded too.
diff --git a/skills/modern-web-guidance/guides/visual-design/adapt-scrollbar-to-contrast-preferences.md b/skills/modern-web-guidance/guides/visual-design/adapt-scrollbar-to-contrast-preferences.md
index aec0295..13daa2c 100644
--- a/skills/modern-web-guidance/guides/visual-design/adapt-scrollbar-to-contrast-preferences.md
+++ b/skills/modern-web-guidance/guides/visual-design/adapt-scrollbar-to-contrast-preferences.md
@@ -2,18 +2,18 @@
Users who enable high-contrast modes in their operating system or browser expect UI elements (like scrollbars) to be extremely legible, often relying on stark foreground-background separation rather than subtle grays or theme colors.
-This guide provides optional instructions on how to use the `@media (prefers-contrast: more)` CSS media feature to enforce high-contrast scrollbar styling.
+This guide provides instructions on how to use the `@media (prefers-contrast: more)` CSS media feature to enforce high-contrast scrollbar styling.
## Enhance Legibility
-When customizing scrollbars with `scrollbar-color` or custom variables, you can provide an explicit override for high-contrast modes. This is especially helpful if your primary application theme uses low-contrast scrollbars for aesthetic reasons.
+When customizing scrollbars with `scrollbar-color` or custom variables, you can provide an explicit override for high-contrast modes. This is especially helpful if your primary application theme uses lower-contrast scrollbars for aesthetic reasons, although the default thumb still needs at least 3:1 contrast against the track (WCAG 1.4.11 Non-text Contrast).
-OPTIONAL: Use a `@media (prefers-contrast: more)` block to define dark, distinct colors for the thumb and track.
+Use an `@media (prefers-contrast: more)` block to define dark, distinct colors for the thumb and track.
```css
/* Define default standard colors as variables */
.scroller {
- --scrollbar-thumb: #bbb;
+ --scrollbar-thumb: #707070;
--scrollbar-track: #f1f1f1;
scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
@@ -21,7 +21,7 @@ OPTIONAL: Use a `@media (prefers-contrast: more)` block to define dark, distinct
scrollbar-gutter: stable;
}
-/* OPTIONAL: Provide clear, high-contrast overrides */
+/* Provide clear, high-contrast overrides */
@media (prefers-contrast: more) {
.scroller {
/* Use extremely distinct colors like solid black against white */
@@ -71,4 +71,3 @@ If you are using custom properties to define colors, these will cascade to the l
}
}
```
-
diff --git a/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md b/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
index accc235..2ad858a 100644
--- a/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
+++ b/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
@@ -251,7 +251,7 @@ Use these options to control hit testing:
### Fallback strategies
-HTML in canvas is not natively supported by any major browser yet.
+HTML-in-canvas is not natively supported by any major browser yet.
The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
diff --git a/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md b/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
index 50f7875..aca32ca 100644
--- a/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
+++ b/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
@@ -12,10 +12,13 @@ Example customizations that are possible:
- **DON'T** apply `user-select: none` to content text — breaks copy-paste, translation tools, and AT "read from here" gestures. Limit it to chrome (drag handles, toolbars, redundant button labels).
- Use `accent-color` to apply the page's accent color to any browser-generated UI.
- Use `color-scheme` to have browser UI adapt to light/dark mode.
-- Use `scrollbar-color` to customize scrollbar colors and `scrollbar-width` to control scrollbar thickness — keep the thumb visibly distinct from the track (≥3:1), and don't set `scrollbar-width: none` on scrollable regions (use it only when scrolling is fully replaced by another affordance).
+- Use `scrollbar-color` to customize scrollbar colors — keep the thumb visibly distinct from the track (contrast ≥3:1)
+- **DON'T** use the `scrollbar-width` with any value other than `auto`, unless another accessible option is provided to scroll content. Although `scrollbar-width: thin` does provide a thumb, the target size of the thumb will be too small for some users to operate.
- Use `:user-invalid` / `:user-valid` for validity styling, **not** `:invalid` / `:valid` — they only match after the user has interacted with the field, avoiding the hostile default of flagging required-empty fields as errors on page load. Exclude range sliders when targeting `input` broadly (e.g., `input:not(input[type="range"]):user-valid`) so adjusting a slider does not apply field validity borders or backgrounds to it.
- Buttons and text fields (including `<textarea>`) can generally be styled as normal elements.
- Use `font-size` to scale and other textual properties to control typography
+- Use text color contrast between the foreground and background colors of at least 4.5:1 for regular size text or at least `3:1` for large-scale text (18 point or 14 point bold font size).
+- Use a contrast between adjacent colors of at least `3:1` for non-text content.
### Styling textual fields (`<input>` & `<textarea>`)
@@ -23,7 +26,8 @@ For most styling purposes (e.g. colors, borders, backgrounds, typography, etc) t
- Use `:placeholder-shown` and `::placeholder` to style input placeholders.
- Use `field-sizing: content` to make text fields size to content.
-- For `<textarea>` elements, use `resize: vertical` to disable horizontal resizing or `resize: none` to disable all resizing.
+- For `<textarea>` elements, use `resize: vertical` to disable horizontal resizing.
+- Do not use `resize: none` on `<textarea>` elements to disable all resizing, without an alternative resizing mechanism, such as using `field-sizing: content;` or providing custom resize buttons.
### Multiple choice controls (select, radios, checkboxes)
diff --git a/skills/modern-web-guidance/guides/visual-design/color.md b/skills/modern-web-guidance/guides/visual-design/color.md
index dc493c3..aa99b71 100644
--- a/skills/modern-web-guidance/guides/visual-design/color.md
+++ b/skills/modern-web-guidance/guides/visual-design/color.md
@@ -2,7 +2,7 @@
## Accessible color
-**Don't use color alone to indicate the presence of a user interface component or its state**: Use iconography and/or shape to help differentiate. Do not denote success/errors ONLY with color. Use icons or text.
+**Don't use color alone to indicate the presence of a user interface component or its state**: Use iconography and/or shape to help differentiate. Do not denote success/errors ONLY with color. Use icons or text (WCAG 1.4.1 Use of Color).
```html
<!-- Good: Denotes state without colors alone -->
@@ -14,12 +14,12 @@
### Contrast
-- **Minimum contrast standards**: Maintain 4.5:1 for normal text and 3:1 for large text or icons.
-- **Ensure non-text contrast standards**: Maintain a minimum contrast ratio of 3:1 for user interface component boundaries and states.
+- **Minimum contrast standards**: Maintain 4.5:1 for normal text and 3:1 for large text (at least 24px, or at least 18.66px bold) or icons (WCAG 1.4.3 Contrast (Minimum) for text, WCAG 1.4.11 Non-text Contrast for icons).
+- **Ensure non-text contrast standards**: Maintain a minimum contrast ratio of 3:1 for user interface component boundaries and states (WCAG 1.4.11 Non-text Contrast).
- This includes visual elements (borders, backgrounds, box-shadows, underlines) that form the boundary or indicate the presence of a UI component (e.g., input field borders).
- - This also includes visual elements indicating active states within a component (e.g., checkbox checkmarks or switch thumbs).
+ - This also includes visual elements indicating active states within a component (e.g., checkbox checkmarks, switch thumbs or custom focus indicators).
- **Caveat**: Meeting 3:1 non-text contrast can challenge minimalistic designs. Soft gradients or subtle inset/outset shadows can soften visual boundaries while satisfying accessibility requirements.
-- **Use `prefers-contrast` only when warranted**: Reach for `@media (prefers-contrast: more)` when the design uses low-contrast accents (e.g., subtle borders, muted secondary text) that need to be reinforced; most sites that already meet baseline contrast won't need it.
+- **Use `prefers-contrast` only when warranted**: Reach for `@media (prefers-contrast: more)` when the design uses low-contrast accents (e.g., subtle borders, muted secondary text) that need to be reinforced; most sites that already meet baseline contrast won't need it. It strengthens colors that already meet the minimums above; it doesn't fix a default that fails them, because it only reaches users who have turned on the setting.
### Light and dark color schemes
@@ -28,9 +28,9 @@ See `dark-mode` (via `npx -y modern-web-guidance@latest retrieve "dark-mode"`) f
### Forced Colors Mode
-- **Support Forced Colors Mode**: In Forced Colors Mode (High Contrast on Windows), the browser overrides author colors with system keywords and strips `background-image`, `box-shadow`, and `border-image`. Define system color fallbacks for color tokens using `@media (forced-colors: active)`.
-- **Use `forced-color-adjust: none` only where color is essential information** (syntax highlighter, color picker swatch). **DON'T** use `forced-color-adjust: none` just to preserve aesthetics.
-- **Don't rely on `background-image`, `box-shadow`, or `border-image` to convey borders, separators, or state**: They disappear in forced colors (and often in print too). If you must, ensure there's an alternative in forced colors mode, such as `outline` or `border` with system color keywords (`CanvasText`, `LinkText`, `ButtonText`, `Highlight`, `GrayText`, etc.).
+- **Support Forced Colors Mode**: In Forced Colors Mode (High Contrast on Windows), the browser overrides author colors with system keywords, removes `box-shadow`, `text-shadow`, and gradient backgrounds, and may also remove `border-image`. `url()` background images can't be relied on either: they may be removed, or kept in their own colors, which may not contrast with the system colors. Define system color fallbacks for color tokens using `@media (forced-colors: active)`.
+- **Use `forced-color-adjust: none` only where color is essential information** (syntax highlighter, color picker swatch). **DON'T** use `forced-color-adjust: none` just to preserve aesthetics. Where the element contains text, set both its text and background colors to a pair that meets the minimums above, because a transparent background shows what is behind it, usually the user's system `Canvas` color, which can be light or dark.
+- **Don't rely on `background-image`, `box-shadow`, or `border-image` to convey borders, separators, or state**: In forced colors they disappear or keep their own colors, which may not contrast with the system colors (and they often disappear in print too). If you must, ensure there's an alternative in forced colors mode, such as `outline` or `border` with system color keywords (`CanvasText`, `LinkText`, `ButtonText`, `Highlight`, `GrayText`, etc.).
## Generating tints
diff --git a/skills/modern-web-guidance/guides/visual-design/contrast-color.md b/skills/modern-web-guidance/guides/visual-design/contrast-color.md
index 687e2d4..f58f80b 100644
--- a/skills/modern-web-guidance/guides/visual-design/contrast-color.md
+++ b/skills/modern-web-guidance/guides/visual-design/contrast-color.md
@@ -1,6 +1,6 @@
# Ensure text readability with dynamic background colors
-When building reusable UI components (like badges or buttons) or supporting dynamic themes, ensuring text is readable against an unpredictable background color can be challenging. The `contrast-color()` CSS function resolves to `black` or `white`, maximizing the contrast ratio against the specified background color.
+When building reusable UI components (like badges, buttons, headers, or footers) or supporting customizable themes, ensuring text remains readable against a variable background color can be challenging. The `contrast-color()` CSS function resolves to `black` (`rgb(0, 0, 0)`) or `white` (`rgb(255, 255, 255)`), maximizing the contrast ratio (targeting at least 4.5:1 WCAG AA contrast) against the specified solid `<color>` value.
## Determine optimal text color
@@ -50,38 +50,27 @@ DO NOT: Hard-code a separate text color for each interaction state when the back
Baseline status for contrast-color(): Newly available. It's been Baseline since 2026-04-10.
Supported by: Chrome 147 (Apr 2026), Edge 147 (Apr 2026), Firefox 146 (Dec 2025), and Safari 26 (Sep 2025).
-To support browsers without `contrast-color()`, you must provide a fallback. If the background color is known and fixed, use a hard-coded contrasting color. For dynamic backgrounds where the color is unknown, choose a strategy from the table below based on your UI requirements and browser support targets.
+To support browsers without `contrast-color()`, you must provide a fallback. If the background color is known and fixed, use a hard-coded contrasting color. For variable background colors (such as theme custom properties where the runtime color is unknown), choose one of the five fallback strategies from the table below based on your UI requirements and browser support targets.
| Strategy | Best For... | Considerations |
| :--- | :--- | :--- |
-| **Relative Color Syntax** | Automated, high-quality CSS-only contrast calculation. | Highest quality CSS-only fallback. |
+| **Calculate contrast with `color(xyz)`** | Automated, CSS-only contrast calculation, ensures compliance with WCAG 1.4.3 Contrast (Minimum). | Highest quality CSS-only fallback. |
| **Text Shadow** | Quick readability boost on any background. | Can look "dirty" or "glowy"; may not fit all designs. |
| **Text Stroke** | Preserving font weight while ensuring edge contrast. | Use `paint-order` to avoid thinning letterforms, if available. |
| **Translucent Overlay** | Ensuring a minimum contrast area behind the text. | Changes the look of the background color under the text, requires a separate text element. |
| **SVG Filters** | Reactive contrast that updates as the background changes. | Requires a separate text element; hacky implementation. |
-### Recommended: Relative Color Syntax (RCS)
+### Recommended: Calculate contrast with `color(xyz)`
-For browsers that support it, RCS provides the most robust automated fallback for dynamic colors.
+In order to adhere to WCAG's 1.4.3 Contrast (Minimum) guideline, calculate the contrasting color using Relative Color Syntax in the CIE XYZ D65 color space, which uses relative luminance as the `y` value. Note that `white` is `color(xyz 0.9505 1 1.089)`, as this is the D65 white point.
Baseline status for Relative colors: Newly available. It's been Baseline since 2024-09-16.
Supported by: Chrome 125 (May 2024), Edge 125 (May 2024), Firefox 128 (Jul 2024), and Safari 18 (Sep 2024).
```css
-@supports (color: oklch(from red l c h)) {
- .badge {
- /* Highest threshold that passes WCAG. Higher values may be more legible. */
- --threshold: 0.623;
- --l: max(0, sign(var(--threshold) - l));
- color: oklch(from var(--badge-bg) var(--l) 0 h);
- }
-}
-
-@supports (color: contrast-color(red)) {
- .badge {
- color: contrast-color(var(--badge-bg));
- }
-}
+--wcag-y-threshold: 0.17913;
+--y: max(0, sign(var(--wcag-y-threshold) - y));
+color: color(from var(--color) xyz-d65 calc(var(--y) * 0.9505) var(--y) calc(var(--y) * 1.089));
```
### Alternative CSS Fallbacks
diff --git a/skills/modern-web-guidance/guides/visual-design/custom-text-decorations.md b/skills/modern-web-guidance/guides/visual-design/custom-text-decorations.md
index 2040149..aa02bd6 100644
--- a/skills/modern-web-guidance/guides/visual-design/custom-text-decorations.md
+++ b/skills/modern-web-guidance/guides/visual-design/custom-text-decorations.md
@@ -230,7 +230,8 @@ If your Baseline target does not support `text-decoration-skip-spaces`, the brow
If your Baseline target does not support `text-decoration-inset`, the
declaration is ignored, so the link keeps its normal, fully visible underline
and the transition has nothing to animate. This is graceful degradation: the
-hover reveal is lost and the link stays underlined.
+hover reveal is lost and the link stays underlined, so no `@supports` check is
+needed.
### Border area
diff --git a/skills/modern-web-guidance/guides/visual-design/customize-scrollbar-color-and-thickness.md b/skills/modern-web-guidance/guides/visual-design/customize-scrollbar-color-and-thickness.md
index 0d9ae8b..8e0aee8 100644
--- a/skills/modern-web-guidance/guides/visual-design/customize-scrollbar-color-and-thickness.md
+++ b/skills/modern-web-guidance/guides/visual-design/customize-scrollbar-color-and-thickness.md
@@ -9,6 +9,8 @@ You can customize the appearance of scrollbars using the standard CSS properties
MANDATORY: Use `scrollbar-color` and `scrollbar-width` on the scrollable container.
+Choose a thumb color with a contrast ratio of at least 3:1 against the track color, and against the container's background where the track may be transparent, such as with macOS overlay scrollbars, so users can see the thumb and how far they've scrolled (WCAG 1.4.11 Non-text Contrast).
+
When using `scrollbar-color`, use CSS variables to keep thumb and track colors separate, for readability and maintainability (especially when using fallbacks).
```css
diff --git a/skills/modern-web-guidance/guides/visual-design/dark-mode.md b/skills/modern-web-guidance/guides/visual-design/dark-mode.md
index dc40bac..b67b7a7 100644
--- a/skills/modern-web-guidance/guides/visual-design/dark-mode.md
+++ b/skills/modern-web-guidance/guides/visual-design/dark-mode.md
@@ -94,7 +94,8 @@ You can use `scrollbar-color` together with `light-dark()` to set custom scrollb
```css
:root {
--color-scrollbar-track: light-dark(#eee, #222);
- --color-scrollbar-thumb: light-dark(#999, #666);
+ /* Example values: the thumb needs at least 3:1 contrast against the track */
+ --color-scrollbar-thumb: light-dark(#6b6b6b, #8a8a8a);
scrollbar-color: var(--color-scrollbar-thumb) var(--color-scrollbar-track);
}
```
@@ -173,11 +174,15 @@ To adapt to the user's preferences in older browsers, use `prefers-color-scheme`
/* Define brand colors for each mode */
--color-brand-light: #0056b3;
--color-brand-dark: #00e5ff;
+ --color-brand-text-light: white;
+ --color-brand-text-dark: #001f24;
--color-brand: var(--color-brand-light);
+ --color-brand-text: var(--color-brand-text-light);
/* MANDATORY: Fallback for browsers without light-dark support */
@media (prefers-color-scheme: dark) {
--color-brand: var(--color-brand-dark);
+ --color-brand-text: var(--color-brand-text-dark);
}
/* Ignored in older browsers */
@@ -186,6 +191,7 @@ To adapt to the user's preferences in older browsers, use `prefers-color-scheme`
button.primary {
background-color: var(--color-brand);
+ color: var(--color-brand-text);
}
```
diff --git a/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md b/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
index 20fdaf4..28f0192 100644
--- a/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
+++ b/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
@@ -316,7 +316,7 @@ Use these options to control hit testing:
## Fallback strategies
-HTML in canvas is not natively supported by any major browser yet.
+HTML-in-canvas is not natively supported by any major browser yet.
The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required. However, given the improved performance benefits of this API, HTML-in-Canvas should be used if the browser supports it.
diff --git a/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md b/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
index 8569975..f8c1c17 100644
--- a/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
+++ b/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
@@ -406,7 +406,7 @@ Use these options to control hit testing:
## Fallback strategies
-HTML in canvas is not natively supported by any major browser yet.
+HTML-in-canvas is not natively supported by any major browser yet.
The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
diff --git a/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md b/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
index fc9aca8..f89f73f 100644
--- a/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
+++ b/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
@@ -421,7 +421,7 @@ function animate() {
### Fallback strategies
-HTML in canvas is not natively supported by any major browser yet.
+HTML-in-canvas is not natively supported by any major browser yet.
The HTML-in-Canvas API is not currently supported in all modern browsers, thus a fallback strategy is typically required.
diff --git a/skills/modern-web-guidance/guides/visual-design/shaped-cutouts.md b/skills/modern-web-guidance/guides/visual-design/shaped-cutouts.md
index 32970f9..83a749b 100644
--- a/skills/modern-web-guidance/guides/visual-design/shaped-cutouts.md
+++ b/skills/modern-web-guidance/guides/visual-design/shaped-cutouts.md
@@ -90,6 +90,8 @@ By assigning both parts the same background color, they visually merge into a si
.unified-card {
display: flex;
width: 400px;
+ /* Shadow on the parent silhouettes the combined card + masked accent shape */
+ filter: drop-shadow(0 10px 20px rgba(0, 0, 0, 0.3));
}
.card-body {
@@ -108,8 +110,8 @@ By assigning both parts the same background color, they visually merge into a si
border-bottom-right-radius: 16px;
/* Reference the SVG mask */
- -webkit-mask-image: url(#card-accent-mask);
- mask-image: url(#card-accent-mask);
+ -webkit-mask-image: url(#accent-stencil);
+ mask-image: url(#accent-stencil);
}
</style>
```
@@ -125,7 +127,7 @@ When you only need simple geometric cutouts (such as a semi-circular top notch,
<style>
.gradient-masked-card {
- background: linear-gradient(135deg, #3b82f6, #1d4ed8);
+ background: linear-gradient(135deg, #2563eb, #1e40af);
color: white;
padding: 40px 24px 24px 24px; /* Extra top padding ensures content clears the notch */
border-radius: 16px;
diff --git a/skills/modern-web-guidance/guides/visual-design/typography.md b/skills/modern-web-guidance/guides/visual-design/typography.md
index 6f2d76a..80ba126 100644
--- a/skills/modern-web-guidance/guides/visual-design/typography.md
+++ b/skills/modern-web-guidance/guides/visual-design/typography.md
@@ -5,15 +5,16 @@
- Use unitless numbers for `line-height` (e.g., `1.5`) to ensure relative scaling during font-size inheritance.
- Use `overflow-wrap: break-word` (or `anywhere`) to contain long URLs.
- **DON'T** use `px` for font-size. Prefer `rem` to honor the user's browser font-size preferences (root font size), or `em`/percentages for contextual sizing.
+- **DON'T** set a fixed `height` or `block-size` on elements that contain text, such as buttons, badges, tabs and cards. Let the content set the height, with `min-block-size` if a minimum is needed, so text doesn't overflow or get clipped when users increase text spacing to a line height of 1.5, spacing after paragraphs of 2em, letter spacing of 0.12em and word spacing of 0.16em (WCAG 1.4.12 Text Spacing requires no loss of content or functionality at these values).
## Readability
- **Avoid long lines of text**: Cap paragraph blocks to a maximum of 80 characters width.
-- **Avoid rivers of whitespace**: Avoid `text-align: justify` as it can make text harder to read. If you must use it, combine it with `hyphens: auto` to avoid excessive whitespace between words.
+- **Avoid rivers of whitespace**: Avoid `text-align: justify` as it can make text harder to read. If you must use it, combine it with `hyphens: auto` to avoid excessive whitespace between words. `hyphens: auto` only hyphenates text whose language is declared with the `lang` attribute, such as `<html lang="en">`.
- **Don't use Ornate fonts**: Omit cursive typefaces for main reading content.
- **Don't rely on all-caps for emphasis**: Prefer bolding for visual emphasis, and use `<em>`/`<strong>` when the emphasis is semantic.
- **Limit emphasis overall**: Emphasis loses meaning when it's everywhere — apply it only where it changes how the content should be read.
-- **Support user zoom preferences**: Allow users to resize text up to 200% without loss of content or functionality.
+- **Support user zoom preferences**: Allow users to resize text up to 200% without loss of content or functionality, and let text reflow at a 320 CSS px viewport width without horizontal scrolling (WCAG 1.4.10 Reflow); avoid `white-space: nowrap` and fixed widths on running text.
```css
body {
@@ -21,7 +22,7 @@ body {
text-align: start; /* Supports LTR and RTL */
}
article {
- max-width: 80ch; /* Caps line length to ~80 characters for readability */
+ max-width: 60ch; /* Caps line length to ~80 characters for readability (1ch is the width of "0", which is wider than most characters) */
}
```
@@ -34,5 +35,5 @@ article {
## Responsive Typography
-- **DO** combine viewport-relative and font-relative units in `clamp()` for font sizes that scale with the viewport size while ensuring they stay within a desired range. For example, `clamp(2rem, 1rem + 5vw, 4rem)`. Adjust the proportion of viewport-relative and font-relative units to control how quickly the font-size changes.
+- **DO** combine viewport-relative and font-relative units in `clamp()` for font sizes that scale with the viewport size while ensuring they stay within a desired range. For example, `clamp(2rem, 1rem + 5vw, 4rem)`. Adjust the proportion of viewport-relative and font-relative units to control how quickly the font-size changes. Use font-relative minimum and maximum values, and keep the maximum no more than 2.5 times the minimum. Viewport units don't grow when users zoom, so the text only grows once its minimum overtakes the viewport-based value; with a maximum no more than 2.5 times the minimum, browser zoom, which goes up to 500%, can still resize the text to 200% (WCAG 1.4.4 Resize Text requires text to resize up to 200% without loss of content or functionality).
- **DON'T** use `vw` alone for font-size without `clamp()`, as it can scale text too small or too large on extreme screens.