This repo is the source repository for GoogleChrome/modern-web-guidance and includes the code and documentation for authoring, calibrating, and evaluating its contents.
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.
See CONTRIBUTING.md and GOVERNANCE.md for how we work on the project and orientation of the codebase.
Stewarded by the Google Chrome, Microsoft Edge, Mozilla Firefox, and MDN teams, alongside the web development community.
Documentation · Eval Dashboard · Source Code · Report an Issue
npx modern-web-guidance@latest installThis command runs an interactive wizard to install Modern Web Guidance. See Alternative Installation Methods below.
Try it out (without installing)
# Search for relevant guides
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 .Coding agents often default to older patterns because LLM training data contains vast amounts of legacy code. This often leads them to generate bloated JavaScript for tasks that now have native, high-performance web platform solutions.
Even if a model knows an API exists, it often lacks the density of real-world, modern implementation patterns required for production-ready code.
Modern Web Guidance bridges this gap. Our skill's CLI returns targeted, expert-curated guidelines directly into your agent's context window, focusing on:
- Modern Browser APIs: Helping models correctly structure APIs they frequently misuse.
- Performance & Accessibility: Preferring platform-level APIs that can be optimized by the browser and include built-in accessibility affordances.
- Responsible Fallbacks: Guiding models to use sensible, lightweight fallbacks instead of heavy polyfills or legacy libraries.
We cover the past several years of the web platform's new features, all the way up to the cutting edge. The guides are designed to be token-efficient; we run evals enabling us to prune lowest-common-denominator content that models already know.
Core Disciplines
🎨 User ExperienceSmooth visual states (View Transitions, entry/exit animations, parallax scroll, CSS |
📐 CSS LayoutModern layout systems (container queries, |
⚡ PerformanceSpeed optimizations (instant preloading, Interaction to Next Paint (INP) diagnostics, and scheduling tasks via |
📝 Forms & UINative components (Anchor Positioning for tooltips, Popover API, dialogs, |
♿ AccessibilityImportant considerations (screen reader and keyboard operability, content navigation and discoverability). |
🤖 Built-in AILocal client models (native translation, summarization, and language detection APIs). |
View an example: the navigation-drawer guide.
The full list
250 modern web features
CSS & Layout (140 features)
HTML & DOM (36 features)
JavaScript & APIs (74 features)
203 real-world developer use cases
accessibility
- accessible-error-announcement: Synchronize programmatic accessibility states (like aria-invalid) with the visual :user-invalid state to ensure screen reader users receive error feedback only after interaction, mirroring the visual experience.
- accessible-generated-content: Use CSS generated content (
::before/::after) in ways that stay accessible, including alternative text for decorative content. - respect-os-text-scale: Respect the operating system's text scale preference for a page so font sizes, layout, and rem-based measurements follow the user's accessibility settings.
built-in-ai
- language-detection: Detect the language of user-generated content or already present site content.
- language-model: Run on-device natural language inference in the browser using the Prompt API, with streaming output, structured JSON responses, and multi-turn session management.
- summarizer: Summarize text content using the on-device Summarizer API.
- translator: Translate text between languages using the on-device Translator API.
css
- animate-to-intrinsic-sizes: Smoothly animate interactive components (like accordions, menus, and expanding cards) to and from their natural dimensions.
- atrule-support-conditionals: Conditionally apply certain CSS rules or declarations only if a certain at-rule is supported by the browser.
- calculate-with-intrinsic-sizes: Calculate the size of an element based on its intrinsic size, while ensuring it fits within given design constraints.
- child-state-based-styling: Build a component that changes its styling based on the state of one of its child elements. For example, a component that renders in light or dark mode based on whether a theme toggle is checked (or not).
- content-based-styling: Build a component that changes its layout based on whether it contains specific child elements (or not). For example, if the component contains an image, use a multi-column layout, otherwise default to a single-column layout.
- css: Action-oriented guidelines for modern CSS architecture, including the cascade, selectors, scoping, nesting, and design tokens. Use this guide when authoring styles or managing design systems.
- css-layout: Modern CSS layouts such as flexbox, grid, subgrid, container queries, anchor positioning, and intrinsic sizing. Use this skill when architecting responsive UI components or page layouts.
- design-token-reactivity: Define higher-order design tokens, like density modes (compact, comfortable, spacious) or themes and have descendant components react to changes directly and in component-appropriate ways.
- dynamic-sibling-styling: Create dynamic visual spectrums or layout arrangements that automatically adapt to the number of elements in a group.
- fluid-scaling: Scale items like font size, spacing, and media sizes smoothly based on the parent container's size rather than using fixed breakpoints
- individual-transform-properties: Animate or override individual CSS transform properties (e.g. translate, rotate, scale) independently of other transform properties on a single element.
- overflow-clipping-control: Adjust the visible clipping boundary of an element to align with the content edge, padding edge, or border edge—or a specified offset from any of these—offering finer-grained control over how content is clipped.
- reduce-style-repetition: Reduce excessive style repetition by encapsulating complex or dynamic styling logic into reusable functions (such as a function that computes a gradient based on a set of input parameters).
- responsive-design: Build UI that adapts to container and viewport size, including container queries, dynamic viewport units, aspect ratios, and responsive typography.
- selector-atrule-combinations: Target elements based on the intersection or union of selectors and conditional @-rules while minimizing repetition.
- size-aware-styling: Build a component whose styles can be conditionally dependent on its own width or height, rather than the width or height of the viewport. For example a card component that can change its layouts depending on how large it is, or a call-to-action button that can conditionally display helper text based on its width.
- style-parent-with-has: Style parent elements of a form field (e.g. labels or fieldsets) when the field is invalid.
- usage-aware-component-variations: Build components that adapt visual logic based on semantic context using CSS container style queries.
forms
- animated-select-picker: 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: Build an address form with correct autocomplete attributes and autofill support.
- autofill-highlight-inputs: Customize the styling of form fields that have been autofilled and not edited by the user
- autofill-payment-form: Build a payment form that collects card details with correct autocomplete values and autofill support.
- autofill-sign-in-form: Build a sign-in form with correct autocomplete values and autofill support.
- autofill-sign-up-form: Build a sign-up form with correct autocomplete values and autofill support.
- brand-consistent-forms: Match checkboxes, radio buttons, range sliders, and progress bars to your site's color palette without replacing them with custom components.
- branded-select-styling: Create custom select elements whose button, picker, arrow icon, and checkmark all seamlessly match your brand or design system's typography, colors, spacing, and border treatments.
- custom-select-picker-layouts: Create custom select pickers whose options are positioned in unique or interesting ways, rather than the traditional stacked list of options.
- form-fields-automatically-fit-contents: Allow form fields to grow and shrink to fit the user input, e.g. as the user types or selects a different option. Apply maximum and minimum size limits to create dynamic and responsive form fields that conform with the page design.
- ime-safe-enter-submit: Implement Enter-to-submit in textareas and single-line inputs (chat, search, inline rename) safely for IME (Input Method Editor) users to prevent submitting incomplete text.
- required-field-feedback: Provide error message for required form fields that were skipped or left empty only after user interaction, to avoid preemptive errors and ensure feedback is timely and contextually relevant to the user's flow.
- rich-media-picker: Create a custom select component whose options can contain complex HTML formatting (e.g. images, icons, and other rich formatting) rather than just plain text.
- select-menu-interaction: Validate that a non-default option has been chosen in a select menu only after the user has interacted with the control.
- slider: Style a native range slider with custom track, thumb, fill, and focus states while preserving native functionality and accessibility.
- sms-otp-form: Verify user phone numbers and one-time passcodes delivered over SMS with automatic code extraction and accessible form input.
- switch: Build an accessible switch with the native HTML switch attribute, falling back to a styled checkbox when not supported.
- validate-input-after-interaction: Show form field validation feedback (e.g. password complexity or email format requirements) only after the user has finished their initial interaction, avoiding premature errors on page load or while the user is typing.
html
- accessible-web-components: Make custom elements accessible by default, setting roles and ARIA state via the ElementInternals ARIA mixin, managing focus with delegatesFocus, and keeping ARIA relationships within a single shadow root.
- custom-elements: Define, register, and manage the lifecycle of autonomous custom elements, covering constructor rules, lifecycle callbacks, upgrade timing, attribute/property reflection, and naming conventions.
- form-associated-custom-elements: Make a custom control participate natively in forms with formAssociated and ElementInternals, submitting its own value, integrating with constraint validation, and reacting to reset, disable, and state-restore.
- prerendering-custom-elements: Server-render a custom element, then hydrate it in place without re-rendering or a flash of unstyled content.
- shadow-dom: Encapsulate a component's DOM and styles with Shadow DOM, construct the tree efficiently with HTML templates, and project consumer content with slots.
- styling-web-components: Style across the shadow boundary with :host selectors, inherited and custom properties for theming, ::slotted and ::part, and cascade layers and container queries inside components.
- web-components: Orientation and cross-cutting principles for authoring and using Web Components, covering Custom Elements, Shadow DOM, templates and slots, Declarative Shadow DOM, styling across the shadow boundary, Form-Associated Custom Elements, and accessibility requirements. Use this guide when building reusable UI components, design systems, or server-rendered custom elements.
js
- calculate-event-differentials: Calculate elapsed or remaining time between dates and times, balance duration units, and format human-readable localized durations using Temporal.Duration and Intl.DurationFormat.
- capture-location-agnostic-data: Model location-agnostic calendar dates, wall-clock times, partial dates (recurring birthdays, credit card expirations), and recurring monthly intervals without time zone drift using Temporal Plain types.
- coordinate-global-events: Schedule future meetings or events by explicitly binding them to a geographical IANA time zone so that event times remain accurate regardless of Daylight Saving Time (DST) transitions, "skipped" or "repeated" hours during clock changes.
- sort-high-precision-timestamps: Parse, sort, and measure intervals between sub-millisecond or nanosecond ISO 8601 timestamps without Date truncation collisions using Temporal.Instant.
- support-global-calendar-systems: Display and calculate dates in non-Gregorian calendar systems (e.g., Islamic, Hebrew, or Chinese) accurately for international users.
performance
- batch-analytics-events: 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: 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: Calculate the total time a user actually spent viewing a page, excluding periods when the tab was in the background.
- conditional-async-dependencies: 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: 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.
- defer-work-until-scroll-ends: Defer expensive operations like DOM updates, data fetching, analytics tracking, or layout recalculation until after scrolling completes to maintain smooth scroll performance.
- deliver-optimized-decorative-images: Deliver optimized decorative images (such as backgrounds, UI icons, or complex masks) by simultaneously providing next-generation image formats (like AVIF or WebP) alongside multiple pixel densities (like 1x and 2x) so the browser can dynamically negotiate the best combination of file size and visual quality for the user's device capabilities.
- deprioritize-background-fetches: Deprioritize background data fetches made with the Fetch API to prevent network contention with user-initiated requests.
- detect-initial-visibility-state: Reliably determine whether a page was initially loaded in the background, even in cases where the script is loaded asynchronously after the user foregrounded the page.
- efficient-background-processing: Conserve system resources and battery life by pausing background JavaScript execution (such as
<canvas>animations, WebGL rendering, or high-frequency WebSocket data polling) when the component is off-screen and then resume them just-in-time when they scroll back into view. - faster-spa-view-transitions: Enable faster transitions back to previously visited views in a Single-Page Application (SPA) by preserving their structural DOM state instead of destroying and rebuilding them on every navigation.
- flicker-free-client-side-ab-testing: Deliver and render A/B tests, multi-variate tests, or other experiments using client-side JavaScript to alter or inject HTML, CSS, and JavaScript without the original content showing first before flickering or flashing to show the experiment content.
- full-session-analytics: Reliably track analytics, Core Web Vitals, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.
- identify-heavy-scripts: Identify the scripts most responsible for long animation frames
- identify-inp-causes: Identify slow-running JavaScript and other causes of poor Interaction to Next Paint (INP) responsiveness.
- improve-next-page-load-performance: Improve page load performance by prefetching or prerendering pages that the user is likely to visit next.
- interaction-paint-timing: Measure the time it takes for user interactions and client-side navigations to render new contentful updates on screen.
- interactions-in-complex-layouts: Make interactions snappier and more responsive (reducing Interaction to Next Paint (INP) scores) by avoiding layout re-calculations in complex layouts, such as data-heavy dashboards or spreadsheet-style grids.
- lazy-load-video-and-audio: Defer downloading offscreen video and audio assets, including video poster images and preloaded media data, until the media player approaches the viewport to conserve bandwidth and reduce network contention during initial page load.
- optimize-image-priority: Optimize the loading priority of Largest Contentful Paint (LCP) candidate images and deprioritize non-critical images to reduce critical resource load delays.
- optimize-preload-priority: Optimize the relative priority of preloaded content to reduce critical resource load delays.
- optimize-script-priority: Optimize the loading priority of scripts by boosting critical asynchronous scripts and deprioritizing non-essential or late-body scripts to improve sequencing and reduce delays.
- out-of-order-html-streaming: Declaratively update a page with content streamed later into the same HTML document or via imperative JavaScript APIs.
- resolution-optimized-pseudo-elements: Use resolution-optimized images in CSS pseudo-elements (such as
::beforeand::after) to reduce the number of DOM nodes. - schedule-tasks-by-priority: Schedule tasks with different priorities to ensure critical work runs first while background work is deferred.
privacy
- privacy: Action-oriented guidelines for web developers to implement privacy by design, data minimization, third-party audits, and secure data handling. Use this skill when designing applications, integrating third-party services, handling user data, or configuring security headers.
pwa
- install-web-app: Install web applications from a page using browser-controlled consent UI.
- migrate-web-app-origin: Transfer an installed web app to a new origin while preserving user configuration and OS-level shortcuts.
security
- client-side-encryption: Establish shared secrets using public-key encapsulation or key agreement—including hybrid and post-quantum protection—and encrypt sensitive data in the browser with authenticated encryption.
- digital-signatures: Sign and verify messages, tokens, or artifacts in the browser using classical or quantum-resistant (post-quantum) asymmetric keys to ensure data integrity and authenticity.
- local-network-access: Access resources on a user's local network or loopback interface from a public web application.
- passkey-authentication: Authenticate a returning user with a passkey for primary sign-in.
- passkey-conditional-create: Silently register a passkey for an existing user after a successful password login.
- passkey-management: Let users view and manage the passkeys registered to their account.
- passkey-reauthentication: Verify a signed-in user's identity using their existing passkeys before a sensitive action.
- passkey-registration: Register a passkey for an existing user account.
- passkeys: Comprehensive orientation and cross-cutting principles for implementing WebAuthn and Passkeys in web applications. Use this guide when handling passkey registration, authentication, management, or reauthentication.
- quick-sign-ins: Authenticate returning users in place with their saved passkeys or passwords before navigating to a sign-in page or interrupting their workflow.
- restrict-outbound-connections: Restrict a page or worker to communicating only with an explicit allowlist of network endpoints to prevent unauthorized third-party requests and client-side data exfiltration.
- sanitize-untrusted-html: Safely parse and display untrusted HTML content from user input by removing unsafe elements and attributes.
- secure-external-subresources: Verify the cryptographic integrity of external scripts, stylesheets, fonts, and images loaded from third-party origins, and control whether those requests send credentials or referrer URLs.
- trusted-types: Prevent DOM-based XSS attacks by defining a Trusted Types policy to sanitize untrusted HTML, using the policy when writing to DOM sinks like innerHTML, and enforcing Trusted Types via Content Security Policy.
- validate-origins: Compare and validate web origins and sites safely across cross-document messages and URLs without error-prone string parsing.
- verify-email-ownership: Verify that a user owns an email address during account creation, sign-in, or recovery without sending a one-time passcode or magic link email.
ui-atoms
- carousel-slide-effects: Create a carousel of slides with images or other visual elements, where each slide animates as they enter/center/exit their scroller. For example, the slides may fade-in/fade-out, rotate, get bigger or smaller, etc.
- component-specific-light-dark-theme: Force certain elements to be in light mode or dark mode (e.g. code blocks, media players, etc) independently of the page's color-scheme.
- icons: Display and manage icons that can be set and parameterized from CSS, are fast to load, crisp at any resolution and are properly exposed to (or hidden from) assistive technologies.
- position-aware-tooltips: Build tooltips and popovers with directional arrows (or other visual styling) that automatically point the correct way when the element flips to a fallback position.
- pull-to-reveal: Build a pull-to-reveal feature that would enable the user to pull down on the screen to reveal more content, like a search bar.
- responsive-table: 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: 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: 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: 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: 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: 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: 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: Position dropdowns, flyouts, or contextual action panels tethered to a trigger button so they automatically flip axes at viewport edges instead of getting clipped.
ui-behaviors
- 2d-panning: Allow users to freely pan or scroll two-dimensional surfaces—such as maps, zoomed images, infinite canvases, or large data grids—across both directions (whether diagonally or changing direction mid-gesture) without the gesture locking to a single horizontal or vertical axis.