# Introduction Open Components is the UXFront component standard: guidelines for building UI components with a perfect user experience, developer experience and agentic experience, whether humans or AI agents write them. Learn the guidelines once, then hold every component to the same high standards, whether you or your agents write it. ## The three layers The standard has three layers, one for each audience a component serves. A component meets the standard when it meets all three. ### User experience Components behave the way people expect them to, with any input, on any device and for every ability. - **Accessible**: keyboard, pointer, touch and screen readers, following [WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/){rel=""nofollow""}. - **Predictable**: the same interaction works the same way in every component. - **Every state**: hover, focus, active, disabled, loading and error, all designed. - **Adaptive**: respects motion, contrast, colour scheme and text size preferences. ### Developer experience One clear API, learned once and used everywhere. Knowing one component means knowing them all. - **Consistent**: sizes, colours, states and events share their names everywhere. - **Type-safe**: every prop, event and slot is typed and documented. - **Composable**: small parts build larger ones, with no hidden coupling. - **Controllable**: controlled or uncontrolled, with every state within reach. ### Agentic experience Agentic experience (AX) is how well AI agents can read, reason about and build with a component. With good AX, their output meets the same bar as yours. - **Semantic**: roles, names and states agents can read straight from the markup. - **Described**: anatomy, props and states, published as machine-readable specs. - **Deterministic**: the same input always renders the same structure. - **Verifiable**: rules agents can check their work against before shipping. ## Foundations Some rules hold for every component rather than for one. [Design Tokens](https://opencomponents.dev/docs/foundations/design-tokens) covers how to name the CSS variables behind them, a convention we call token paths, and the theme tokens they all share. ## Components Each component page holds one component to the three layers, and also covers how it looks, which we call its UI. Every page follows the same structure, so you and your agents always know where to look: - **At a glance**: a single table with its element, role, keyboard support and options. - **UI**: its anatomy, variants, colours, sizes, states and tokens. - **UX**, **DX** and **AX**: the three layers, one trait at a time. - **Checklist**: every rule, with a stable ID like `button/keep-focus`, a level, a scope that says whether the component or the code using it meets the rule, a basis that says where it comes from, like a WCAG success criterion or our own call, and a way to check it. - **Reference implementation**: a component that does its part of every rule, along with its tests. The code is in Vue for now. [All components](https://opencomponents.dev/docs/components) lists every component page we've published, with links to its layers. The [Button](https://opencomponents.dev/docs/components/button) is a great place to start, and the [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap) lists the components we plan to ship next. ## For agents If your agent supports MCP, connect it to our [MCP server](https://opencomponents.dev/docs/getting-started/mcp-server) at `https://mcp.opencomponents.dev/mcp`. It gives your agent the contracts, every rule and the docs as tools, so it reads a component's contract first, then only the sections it needs rather than the whole page. Our [agent plugin](https://opencomponents.dev/docs/getting-started/agent-plugin) connects the server for you, along with skills that build and review components the way the standard asks, so your agent follows it without being told how. It works in VS Code, GitHub Copilot, Cursor, Codex, Claude Code and other clients that support [Agent Plugins](https://agent-plugins.org){rel=""nofollow""}. Every page of these docs is also published as markdown: prefix its path with `/raw` and add `.md`, as in [`/raw/docs/getting-started/introduction.md`](https://opencomponents.dev/raw/docs/getting-started/introduction.md){external=""}. [`/llms.txt`](https://opencomponents.dev/llms.txt){external=""} lists every page, and [`/llms-full.txt`](https://opencomponents.dev/llms-full.txt){external=""} holds them all in one file. Pages that describe a contract, like the Button's, also publish it on its own, with every rule from their checklist: swap `.md` for `.yaml`, as in [`/raw/docs/components/button.yaml`](https://opencomponents.dev/raw/docs/components/button.yaml){external=""}. It's a fraction of the page's length, for when an agent only needs the rules, and not the reasoning behind them. Every contract follows the same [JSON Schema](https://opencomponents.dev/schemas/contract.json){external=""}, so you and your agents can validate one, including a contract you write for a component of your own. Each contract names the schema on its first line, so editors that use the YAML language server, like VS Code with its YAML extension, check it as you type. # Roadmap Open Components grows one component at a time. We'd love to cover every component you reach for, but a page only helps you if you can trust it, so we write each one in full before we move on to the next. This page shows you where we are, and what's coming next. Every component gets a page with the same structure as the [Button](https://opencomponents.dev/docs/components/button)'s, so you always know where to look: - **User Interface** (UI) - how it looks, from its anatomy to its tokens - **User Experience** (UX) - how it behaves for every person and every input - **Developer Experience** (DX) - how developers work with it - **Agentic Experience** (AX) - how agents can read and verify it On top of that, each page comes with a checklist of every rule, a contract your agents can check their work against, and a reference implementation that does its part of every rule, along with the tests that prove it. That's a lot to get right, so a page only ships once all of it is ready. We'd much rather give you one page you can rely on than several you can't. ## Components Here's every component we plan to cover. A tick means its page has shipped, so you can read it today. We've grouped them by what they build on, so each group can reuse what the ones before it have already settled, like the Button's sizes and colours, or how the Dialog handles focus. The order may still change as we go, and you can help shape it. ### Actions and forms Let's start with the components people use to act and to fill in forms. The Button sets the sizes, colours and states that every other component shares, and the form controls build on them with the labels, hints, validation and controlled values that every form needs. The Tag takes over the removable tags the Select settled, so other components can share them, and the Tag Group lays them out as a named list that keeps focus in place as they're removed. | Component | What it's for | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | [Button](https://opencomponents.dev/docs/components/button) | Acting on what's in front of you, from saving a form to deleting a file | | [Field](https://opencomponents.dev/docs/components/field) | Labelling a form control, with a hint and an error message when it needs them | | [Input](https://opencomponents.dev/docs/components/input) | Typing a single line of text, like a name, an email address or a search | | [Textarea](https://opencomponents.dev/docs/components/textarea) | Writing longer text, like a comment or a message | | [Checkbox](https://opencomponents.dev/docs/components/checkbox) | Saying yes or no to one thing, like agreeing to the terms | | [Checkbox Group](https://opencomponents.dev/docs/components/checkbox-group) | Picking any number of options out of a few | | [Radio Group](https://opencomponents.dev/docs/components/radio-group) | Picking one option out of a few, when they all fit on the screen | | [Switch](https://opencomponents.dev/docs/components/switch) | Flipping a setting on or off, with an effect you see right away | | [Select](https://opencomponents.dev/docs/components/select) | Picking one option, or several, out of many, from a list | | [Tag](https://opencomponents.dev/docs/components/tag) | Labelling what something is about, like a topic or a picked value, that people can remove or follow | | [Tag Group](https://opencomponents.dev/docs/components/tag-group) | Showing a set of tags, like an issue's labels or a search's filters, that people can remove one by one | ### Overlays Next come the components that sit on top of the page. They all need to take focus and give it back, close with `Escape` or a click outside, and stack in the right order, so we'll settle those rules once and share them. | Component | What it's for | | -------------------------------------------------------------- | ----------------------------------------------------------------------------- | | [Dialog](https://opencomponents.dev/docs/components/dialog) | Asking for someone's full attention, and holding focus until they're done | | [Popover](https://opencomponents.dev/docs/components/popover) | Showing more next to what opened it, without blocking the rest of the page | | [Tooltip](https://opencomponents.dev/docs/components/tooltip) | Giving a short hint on hover and focus, like an icon-only button's label | | Dropdown Menu | Tucking a list of actions behind a single button | | Toast | Confirming something briefly without getting in the way, like "Changes saved" | ### Navigation and disclosure These help people find their way around a site, or show and hide what's on a page. Most of them build on the Link and the Button, and add the keyboard support people expect, like moving between tabs with the arrow keys. | Component | What it's for | | ----------- | ------------------------------------------------------------------ | | Link | Taking people somewhere else, from inside a sentence or on its own | | Tabs | Switching between panels of related content, one at a time | | Accordion | Expanding and collapsing sections, like the questions in an FAQ | | Breadcrumb | Showing where a page sits in the site, and the way back up | | Pagination | Moving through a long list of results, a page at a time | ### Feedback and display These tell people what's going on, and most of them aren't interactive at all. That's why their rules are mostly about meaning and contrast, and about making sure screen readers hear about what changes. | Component | What it's for | | -------------------------------------------------------------- | --------------------------------------------------------------------------------- | | [Spinner](https://opencomponents.dev/docs/components/spinner) | Showing that something is busy, for a wait of unknown length | | Alert | Telling people something important, from a success to an error, right on the page | | Badge | Marking a status or a count, like "New" or "3" | | Avatar | Showing a person or a team, with a photo, their initials or an icon | | Progress | Showing how far along a task is, even when you can't tell how long it'll take | | Skeleton | Holding the layout while content loads, so nothing jumps around when it arrives | | [Card](https://opencomponents.dev/docs/components/card) | Grouping related content, like a project or a product, in one container | ### Later Finally, the composite widgets. They have the most keyboard behaviour of all, and they build on almost everything above, which is why they come last. A combobox, for example, is an input, a popover and a list working together. | Component | What it's for | | ---------------------------------------------------------------- | -------------------------------------------------------------------- | | [Combobox](https://opencomponents.dev/docs/components/combobox) | Typing to filter a list of suggestions, like when you pick a country | | Slider | Picking a value or a range by dragging, or with the arrow keys | | Date Picker | Typing a date or a range, or picking it from a calendar | | Table | Comparing rows of data, with sorting and selection | | Tree View | Browsing nested items, like the folders in a file explorer | | Command Palette | Finding any action from the keyboard, just by typing its name | ## Before a page ships You don't have to wait for a page to hold a component to the standard. The three layers in the [Introduction](https://opencomponents.dev/docs/getting-started/introduction) apply to every component, [Design Tokens](https://opencomponents.dev/docs/foundations/design-tokens) covers how to name its variables, and the [Button](https://opencomponents.dev/docs/components/button) shows how the layers turn into rules you can check. Your agents can do the same. Point them at [`/llms-full.txt`](https://opencomponents.dev/llms-full.txt){external=""}, which holds the whole standard in one file, and ask them to follow the Button's structure. For a component that doesn't have its page yet, you could use: ```text Build a Tabs component for our design system that meets the Open Components standard: https://opencomponents.dev/llms-full.txt There's no Tabs page yet, so follow the Button page's structure. Work through the UI, UX, DX and AX of tabs, following the WAI-ARIA Tabs pattern, then write a checklist with a stable ID for every rule, like tabs/arrow-keys, and a test for each one. ``` ## Suggest a component Is a component you need missing, or further down the list than you'd like? [Open an issue](https://github.com/uxfront-com/open-components/issues/new/choose){rel=""nofollow""} and tell us what you're building with it. Knowing what you need helps us decide what comes next. # MCP Server Our MCP server gives your agents the whole standard as tools: the contracts, every rule, the docs and the reference implementations. Connect it once, then ask your agent to build or review a component. It reads only what the task needs, then checks its work rule by rule, citing each rule by its ID. It works with Claude, ChatGPT, Codex, Cursor, VS Code, GitHub Copilot, Gemini CLI and any other client that supports remote servers over the [Model Context Protocol](https://modelcontextprotocol.io){rel=""nofollow""}. It's free, with nothing to install and no account or API key to set up. This page covers: - **Quick start** - connect it and try it in a minute - **Connect your client** - the setup for each client, step by step - **What you can ask** - prompts for building, reviewing and learning the standard - **How it works** - what your agent reads, and in what order - **Tools, prompts and resources** - everything the server offers - **Privacy and security** - what it sees, and what it can't do - **Troubleshooting** - what to check when it doesn't connect ## At a glance | Aspect | MCP server | | -------------- | ------------------------------------------------------------------------------------------------------------- | | URL | `https://mcp.opencomponents.dev/mcp` | | Name | `open-components`, the name to add it under | | Transport | Streamable HTTP | | Authentication | None, so where a client asks, choose none | | Access | Read-only. It serves the standard and changes nothing | | Cost | Free | | Tools | `list-components`, `get-contract`, `list-rules`, `get-page`, `search-docs` and `get-reference-implementation` | | Prompts | `build-component`, `review-component`, `review-usage` and `adopt-token-paths` | | Content | The same files as this site, redeployed whenever they change | ## Quick start ::steps{level="3"} ### Add the server In a coding agent, it takes one command: :::code-group ```bash [Claude Code] claude mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` ```bash [Codex] codex mcp add open-components --url https://mcp.opencomponents.dev/mcp ``` ```bash [Gemini CLI] gemini mcp add --scope user --transport http open-components https://mcp.opencomponents.dev/mcp ``` ```bash [Copilot CLI] copilot mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` ::: In an editor, open the [Cursor install link](https://mcp.opencomponents.dev/mcp/deeplink){rel=""nofollow""} or the [VS Code install link](https://mcp.opencomponents.dev/mcp/deeplink?ide=vscode){rel=""nofollow""}. On every page of these docs, the menu next to **Copy page** can also copy the server's URL for you, with **Copy MCP Server URL**, or install it in Cursor, with **Add MCP Server**. For any other client, see [Connect your client](https://opencomponents.dev/#connect-your-client). To get skills that build and review components along with the server, install our [agent plugin](https://opencomponents.dev/docs/getting-started/agent-plugin) instead. ### Check that it's connected Run `/mcp` in Claude Code, Codex or Gemini CLI, or `/mcp show open-components` in Copilot CLI, to check that `open-components` is connected. In an editor, look for it in the MCP settings, along with its six tools. ### Ask your agent Ask for what you need in your own words. Mention the server by name the first time, so your agent knows to reach for it: ```text Build a Button component for our React design system that meets the Open Components standard, using the open-components MCP server. Check your work against every rule with a component or both scope, and cite the rule ID for any rule you can't meet. ``` [What you can ask](https://opencomponents.dev/#what-you-can-ask) has more prompts to start from. :: ## Connect your client Every client needs the same three things: the URL, `https://mcp.opencomponents.dev/mcp`, the name, `open-components`, and no authentication. Most take a single command or a few lines of configuration. There's nothing to sign in to, so where a client asks about authentication, choose none. ### Coding agents ::tabs :::tabs-item{label="Claude Code"} ```bash claude mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` That adds it for you, in the project you're in. Add `--scope user` to use it in every project, or `--scope project` to share it with your team through the project's `.mcp.json`, which asks each of them to approve it once. Run `/mcp` in Claude Code to check that it's connected. ::: :::tabs-item{label="Codex"} ```bash codex mcp add open-components --url https://mcp.opencomponents.dev/mcp ``` That adds it to `~/.codex/config.toml`, which the Codex CLI, the Codex extension for your editor and Codex in the ChatGPT desktop app all read. To share it with your team, add it to `.codex/config.toml` in your project instead, which Codex reads once you trust the project: ```toml [.codex/config.toml] [mcp_servers.open-components] url = "https://mcp.opencomponents.dev/mcp" ``` Run `/mcp` in Codex to check that it's connected. ::: :::tabs-item{label="Gemini CLI"} ```bash gemini mcp add --scope user --transport http open-components https://mcp.opencomponents.dev/mcp ``` That adds it to `~/.gemini/settings.json`, which Gemini Code Assist's agent mode in VS Code (Standard and Enterprise) reads too, after **Developer: Reload Window**. Leave out `--scope user` to add it to `.gemini/settings.json` in the folder you're in instead, and start `gemini` from that folder, though not from your home folder, where it reports success but saves nothing. Run `/mcp` in Gemini CLI to check that it's connected. ::: :::tabs-item{label="Copilot CLI"} ```bash copilot mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` That adds it to `~/.copilot/mcp-config.json`. Run `/mcp show open-components` in a Copilot CLI session to check that it's connected. ::::note On Copilot Business and Enterprise, an organization owner turns on the **MCP servers in Copilot** policy first. :::: ::: :::tabs-item{label="Grok Build"} In Grok Build, xAI's coding agent: ```bash grok mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` That adds it to `~/.grok/config.toml`. Run `grok mcp doctor open-components` to check that it's connected. ::: :::tabs-item{label="Hermes Agent"} ```bash hermes mcp add open-components --url https://mcp.opencomponents.dev/mcp ``` Answer `n` when it asks whether the server needs authentication, then let it enable every tool. That adds it to `~/.hermes/config.yaml` (`%LOCALAPPDATA%\hermes\config.yaml` on Windows), which you can also edit yourself: ```yaml [~/.hermes/config.yaml] mcp_servers: open-components: url: "https://mcp.opencomponents.dev/mcp" ``` Run `hermes mcp test open-components` to check that it's connected. In the Hermes desktop app, add it under **Capabilities > Connectors > Add your own**: set **Type** to **Streamable HTTP**, leave **Auth** on **None** and click **Save**. ::: :: ### Editors ::tabs :::tabs-item{label="Cursor"} Open the [Cursor install link](https://mcp.opencomponents.dev/mcp/deeplink){rel=""nofollow""}, or add the server to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` to use it in every project: ```json [.cursor/mcp.json] { "mcpServers": { "open-components": { "url": "https://mcp.opencomponents.dev/mcp" } } } ``` ::: :::tabs-item{label="VS Code"} Open the [VS Code install link](https://mcp.opencomponents.dev/mcp/deeplink?ide=vscode){rel=""nofollow""}, or add the server to a `.mcp.json` at your project's root, which Claude Code reads too: ```json [.mcp.json] { "mcpServers": { "open-components": { "type": "http", "url": "https://mcp.opencomponents.dev/mcp" } } } ``` In `.vscode/mcp.json`, the same entry goes under `servers` rather than `mcpServers`. Copilot Chat can then use its tools in agent mode. ::::note On Copilot Business and Enterprise, an organization owner turns on the **MCP servers in Copilot** policy first. :::: ::: :::tabs-item{label="Visual Studio"} Add the server to `.mcp.json` in your solution, or to `%USERPROFILE%\.mcp.json` to use it in every solution: ```json [.mcp.json] { "servers": { "open-components": { "type": "http", "url": "https://mcp.opencomponents.dev/mcp" } } } ``` Then turn on its tools from **Tools** in Copilot Chat's agent mode. ::::note On Copilot Business and Enterprise, an organization owner turns on the **MCP servers in Copilot** policy first. :::: ::: :::tabs-item{label="JetBrains"} In AI Assistant 2025.3 or later, go to **Settings > Tools > AI Assistant > Model Context Protocol (MCP)**, click **Add**, choose **HTTP** and paste: ```json { "mcpServers": { "open-components": { "url": "https://mcp.opencomponents.dev/mcp" } } } ``` Click **OK**, then **Apply**. To let Junie and the other agents in your IDE use it too, turn on **Pass custom MCP servers** under **Settings > Tools > AI Assistant > Agents**. For Junie CLI, add the same entry to `~/.junie/mcp/mcp.json`, or to `.junie/mcp/mcp.json` in your project. ::: :::tabs-item{label="Zed"} Add it under **Settings > AI > MCP Servers > Add Server > Add Remote Server** (in older releases, in the Agent Panel's settings), or to `context_servers` in your `settings.json`: ```json [settings.json] { "context_servers": { "open-components": { "url": "https://mcp.opencomponents.dev/mcp" } } } ``` The dot next to it turns green once it's connected. ::: :::tabs-item{label="Antigravity"} ```bash agy mcp add open-components https://mcp.opencomponents.dev/mcp ``` That adds it to `~/.gemini/config/mcp_config.json`, which the Antigravity CLI, the IDE and the desktop app share. In the IDE, open it from the agent panel's **…** menu, under **MCP Servers > Manage MCP Servers > View raw config**. Give a remote server a `serverUrl` there, the key Antigravity's docs ask for: ```json [~/.gemini/config/mcp_config.json] { "mcpServers": { "open-components": { "serverUrl": "https://mcp.opencomponents.dev/mcp" } } } ``` ::: :::tabs-item{label="Windsurf and Devin"} In Windsurf, add the server to `~/.codeium/windsurf/mcp_config.json`: ```json [~/.codeium/windsurf/mcp_config.json] { "mcpServers": { "open-components": { "serverUrl": "https://mcp.opencomponents.dev/mcp" } } } ``` With the Devin CLI: ```bash devin mcp add -s user open-components https://mcp.opencomponents.dev/mcp ``` ::: :: ### Chat apps ::tabs :::tabs-item{label="Claude"} In Claude and Claude Desktop, add the server as a custom connector: 1. Go to **Customize > Connectors**, click **+ Add**, then **Add custom connector**. 2. Name it `open-components` and enter the URL. 3. Under **Authentication**, choose **No sign in**. You can then turn it on for a conversation from the **+** button, under **Connectors**. ::::note On Team and Enterprise plans, an owner adds it for everyone first, under **Organization settings > Connectors** . :::: ::: :::tabs-item{label="ChatGPT"} You can add it on the web, with a Plus, Pro, Business, Enterprise or Edu plan: 1. Turn on **Developer mode** in ChatGPT's settings. 2. Create an app named `open-components` with the URL, set **Authentication** to **No Authentication** and confirm that you trust the server. 3. In a new chat, pick it from the **+** menu, under **Developer mode**. The menus can differ a little from plan to plan. ::::note On Enterprise and Edu workspaces, an admin allows **Developer mode** first. On Business, only admins and owners can use it, so they add the app for everyone. :::: ::: :::tabs-item{label="Grok"} On [grok.com](https://grok.com/connectors){rel=""nofollow""}: 1. Open **Connectors**, choose **New Connector**, then **Custom**. 2. Name it `open-components`, enter the URL as its **Server URL** and click **Add Connector**. ::::note On Grok Business and Enterprise, an admin adds it for everyone first, in the xAI console under **Grok Business > Connectors** . :::: ::: :: ### Cloud agents and APIs ::tabs :::tabs-item{label="Copilot cloud agent"} For Copilot's cloud agent on github.com, a repository admin pastes this under the repository's **Settings > Copilot > MCP servers**, then clicks **Save MCP configuration**: ```json { "mcpServers": { "open-components": { "type": "http", "url": "https://mcp.opencomponents.dev/mcp", "tools": ["*"] } } } ``` ::::note On Copilot Business and Enterprise, an organization owner turns on the **MCP servers in Copilot** and **Copilot cloud agent** policies first. :::: ::: :::tabs-item{label="xAI API"} Pass the server to the Responses API as a tool, and xAI connects to it for you: ```json "tools": [ { "type": "mcp", "server_url": "https://mcp.opencomponents.dev/mcp", "server_label": "open-components" } ] ``` ::: :: ### Other clients - **Amp**: ```bash amp mcp add open-components https://mcp.opencomponents.dev/mcp ``` - **Cline**: open **Customize** (the wrench), then **MCP > Add Remote Server**, and keep **Streamable HTTP** as its transport. - **Continue**: add the server to the `mcpServers` list in `~/.continue/config.yaml`. Continue uses it in Agent and Plan modes. ```yaml mcpServers: - name: open-components type: streamable-http url: https://mcp.opencomponents.dev/mcp ``` - **Crush**: from Crush 0.88, add this line to `~/.config/crush/crushrc`: ```bash mcp add open-components --type http --url https://mcp.opencomponents.dev/mcp ``` - **Factory Droid**: ```bash droid mcp add open-components https://mcp.opencomponents.dev/mcp --type http ``` - **goose**: in the desktop app, go to **Extensions > Add custom extension**, choose **Streamable HTTP** as its type and enter the URL as its endpoint. In the CLI, run `goose configure` and choose **Add Extension > Remote Extension (Streamable HTTP)**. - **LM Studio**: add the server under `mcpServers` in `~/.lmstudio/mcp.json`, which **Program > Install > Edit mcp.json** opens: ```json { "mcpServers": { "open-components": { "url": "https://mcp.opencomponents.dev/mcp" } } } ``` - **OpenCode**: ```bash opencode mcp add open-components --url https://mcp.opencomponents.dev/mcp ``` :brIn releases from before June 2026, run `opencode mcp add` and answer its questions instead. - **Qwen Code**: ```bash qwen mcp add --transport http open-components https://mcp.opencomponents.dev/mcp ``` - **Warp**: under **Settings > Agents > MCP servers**, click **+ Add** and paste: ```json { "open-components": { "url": "https://mcp.opencomponents.dev/mcp" } } ``` Any other client that supports remote MCP servers over streamable HTTP only needs the URL. If yours only runs local servers, it can still reach this one through [mcp-remote](https://www.npmjs.com/package/mcp-remote){rel=""nofollow""}, which you add as a local server with this command: ```bash npx -y mcp-remote https://mcp.opencomponents.dev/mcp ``` ## What you can ask Once the server is connected, ask in your own words. Mention it by name the first time, and your agent takes it from there: the server tells it which tools to use, and in what order. Here's what it can help with, and a prompt to start from for each. ### Build a component ```text Build a Button component for our React design system that meets the Open Components standard, using the open-components MCP server. Check your work against every rule with a component or both scope, and cite the rule ID for any rule you can't meet. ``` Your agent reads the Button's contract with `get-contract`, ports the reference implementation and its tests from `get-reference-implementation`, and reads how the API looks in React with `get-page`. Then it checks its work against the contract's rules with a component or both scope. For a component on the [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap), which has no contract yet, it holds it to the three layers and Design Tokens instead, following the Button's structure. The `build-component` prompt asks for the same. ### Review a component ```text Review our Button, in src/components/Button.tsx, against the Open Components standard, using the open-components MCP server. Report every rule with a component or both scope as pass or fail, with its rule ID and the evidence from our code. Then fix the failures. ``` Your agent lists the rules to report on with `list-rules`, then checks your code against each one. For a rule it's unsure of, it finds the section that explains it with `search-docs`, and reads it with `get-page`. The `review-component` prompt asks for the same. ### Review a screen ```text Review how our checkout page uses buttons against the Open Components standard, using the open-components MCP server. Report every rule with a usage or both scope as pass or fail, with its rule ID and the evidence from our code. ``` Usage rules are the ones the code using a component meets, like `button/one-primary`, which keeps one solid primary button per view. Your agent lists them with `list-rules`, with a usage or both scope. The `review-usage` prompt asks for the same. ### Move to token paths ```text Rename our CSS variables to follow the Open Components token paths, using the open-components MCP server. List our token groups first, then rename every variable along with every var() that reads it, keeping the values as they are. Then add the Stylelint rule from the standard, and fix anything it reports. ``` Your agent reads the [Design Tokens](https://opencomponents.dev/docs/foundations/design-tokens) contract with `get-contract`, and the Stylelint rule from the page's Lint section with `get-page`. The `adopt-token-paths` prompt asks for the same. ### Learn the standard ```text Using the open-components MCP server, how should a button behave while it's loading? Link to the sections you used. ``` Your agent finds the sections that cover it with `search-docs`, then reads them with `get-page`, with the examples in your framework if you name one. To see what the standard covers so far, and what's planned, ask which components it has, and your agent lists them with `list-components`. ## How it works You could point your agent at a page instead, but component pages are long. The Button's is about 35,000 tokens, mostly reasoning and examples in seven frameworks, which is far more than any one task needs. Its contract holds every requirement in about 3,000. When your agent connects, the server tells it how to use it, so you don't have to. Your agent: 1. **Finds what the task is about**, with `list-components`, or `search-docs` for a topic. 2. **Reads the contract first**, with `get-contract`: the component's API, its DOM contract, its tokens and every rule. 3. **Reads only the sections it needs**, with `get-page`, for the reasoning or an example behind a rule, in your framework. 4. **Starts from the reference implementation**, with `get-reference-implementation`, when it builds a component. 5. **Checks its work rule by rule**, with `list-rules`, citing every rule by its ID, like `button/keep-focus`, exactly as the server writes it, so you can look each one up. ### Rules and scopes Every rule has a level. A component meets the standard when it meets every must rule, and each should rule is expected unless there's a good reason not to follow it. A component's rules also have a scope, which says whose code to check them against: | Scope | Met by | Check it when you | | ----------- | ------------------------------------------------- | --------------------------- | | `component` | The component itself | Build or review a component | | `usage` | The code that uses it | Review a screen | | `both` | The two together, like naming an icon-only button | Do either | ### Always in step with the site The server is built from the same files as this site, and redeployed whenever they change, so it serves the standard exactly as the site publishes it. A contract from `get-contract` is the same file as its `/raw/docs/.yaml`, and a page from the resources is the same as its `/raw/docs/.md`. ## Tools, prompts and resources ### Tools Your agent calls these on its own, following the instructions the server gives it. Every tool is read-only, and tells your client so. | Tool | What it returns | Arguments | | ------------------------------ | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `list-components` | What the standard covers, shipped or planned, with the name the other tools take, like `button` | Optionally, `status` | | `get-contract` | The contract of a component or foundation, as YAML: its API, its DOM contract, its tokens and every rule | `component` | | `list-rules` | Rules as records, each with its ID, level, scope, requirement and how to check it, 50 at a time | Optionally, `component`, `ids`, `scope`, `layer`, `level`, `check` or `automated`, and `offset` and `limit` | | `get-page` | A page, or only the sections you name, with the examples in one framework | `path`, and optionally `sections` and `framework` | | `search-docs` | The sections and rules that best match a query, across the whole standard | `query`, and optionally `component`, `type` and `limit` | | `get-reference-implementation` | A component's reference implementation in Vue 3 and its tests, or only the files you name | `component`, and optionally `files` | A page longer than about 8,000 tokens, like the Button's, comes back as its outline, every heading with its anchor and length, so your agent can ask for the sections it needs. `list-rules` returns up to 50 rules at a time, with `total` counting every rule that matches and `nextOffset` when there are more, which your agent passes as `offset` to get the next page. No reply is longer than about 36,000 characters, so clients like Gemini CLI and Codex pass it on whole. ### Prompts Prompts are requests you start yourself, usually as slash commands. They ask for what the prompts on our pages ask for, then point your agent at the tools. | Prompt | What it does | Arguments | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | `build-component` | Builds a component in your framework, from its contract, reference implementation and tests, or for one on the Roadmap, following the Button's structure | `component`, and optionally `framework` | | `review-component` | Reviews the code of a component or foundation, reporting every rule as pass or fail with its ID and the evidence, then fixes the failures | `component`, and optionally `code` | | `review-usage` | Does the same for a screen that uses a component, against the rules the screen meets | `component`, and optionally `screen` | | `adopt-token-paths` | Renames your CSS variables to [token paths](https://opencomponents.dev/docs/foundations/design-tokens), then adds the Stylelint rule that keeps them that way | None | How you start one depends on your client: | Client | Command | | ----------- | ------------------------------------------------------------------------- | | Claude Code | `/mcp__open-components__build-component button react` | | Gemini CLI | `/build-component button --framework=react` | | VS Code | `/mcp.open-components.build-component`, which then asks for its arguments | Not every client runs them: Codex doesn't, and Continue, OpenCode and Zed can't pass their arguments yet, so only `adopt-token-paths` works there. Where yours doesn't, ask for the same in your own words, as in [What you can ask](https://opencomponents.dev/#what-you-can-ask), or install our [agent plugin](https://opencomponents.dev/docs/getting-started/agent-plugin), whose skills your agent picks up on its own. ### Resources Resources are files you attach to a conversation yourself, with `@` in Claude Code, or **Add Context > MCP Resources** in VS Code. They're every contract and every page, at the same URLs as on this site, `/raw/docs/.yaml` and `.md`, and the [contract schema](https://opencomponents.dev/schemas/contract.json){external=""}. ## Privacy and security The server only serves the standard, so there's little that can go wrong, but here's exactly what it does and doesn't do: - **It's read-only.** Its tools read the standard and change nothing, on our side or in your project. Your agent makes every change to your code itself, with the permissions you give it. - **It takes no credentials.** There's no account, API key or token, so there's nothing to set up, store or leak. - **It only sees what your agent sends it.** Each call carries a few arguments, like a component's name, a search query or the sections to read. The exception is the `code` and `screen` arguments of the review prompts, which send whatever you pass in. To keep your code on your machine, pass the paths of your files instead, like `src/components/Button.tsx`, and your agent reads them itself. - **It serves what the site publishes.** Everything it returns comes from the same files as this site, in its [public repository](https://github.com/uxfront-com/open-components){rel=""nofollow""}, so you can read any of it before your agent does. ## Troubleshooting ::accordion :::accordion-item{label="My client doesn't list the server, or its tools"} Check that the URL is exactly `https://mcp.opencomponents.dev/mcp`, with `/mcp` at the end, and that the client connects to it over HTTP, which some clients call streamable HTTP, rather than SSE. Then restart the client, or reload its window, since many only read their MCP settings when they start. Some clients keep remote servers under their own key. In `.vscode/mcp.json` and Visual Studio's `.mcp.json`, the server goes under `servers` rather than `mcpServers`, and Antigravity and Windsurf ask for a `serverUrl` rather than a `url`. Gemini CLI saves nothing when you add the server to a project from your home folder, so use `--scope user` there. ::: :::accordion-item{label="My client asks me to sign in"} The server takes no credentials, so there's nothing to sign in to. Choose none, which clients call **No sign in** , **No Authentication** or **None** , and if a command asks whether the server needs authentication, answer no. ::: :::accordion-item{label="My agent doesn't use the server"} Mention it by name, as in "using the open-components MCP server", at least the first time. In Claude and ChatGPT, check that it's turned on for the conversation, and in Visual Studio and JetBrains IDEs, that its tools are turned on for your agent (see [Editors](https://opencomponents.dev/#editors) ). ::: :::accordion-item{label="My client only runs local servers"} It can still reach this one through [mcp-remote](https://www.npmjs.com/package/mcp-remote){rel=""nofollow""}, which runs on your machine and passes every request on. Add it as a local server with this command: ```bash npx -y mcp-remote https://mcp.opencomponents.dev/mcp ``` ::: :::accordion-item{label="A page came back as an outline"} That's on purpose. A page longer than about 8,000 tokens comes back as its outline, so your agent can ask for the sections it needs rather than fill its context with the whole page. It usually does on its own, and naming your framework keeps only its examples. ::: :::accordion-item{label="The prompts don't show up"} Not every client supports MCP prompts. Codex doesn't, and Continue, OpenCode and Zed can't pass their arguments yet, so only `adopt-token-paths` works there. Ask for the same in your own words instead, as in [What you can ask](https://opencomponents.dev/#what-you-can-ask) : the tools are all your agent needs. Or install our [agent plugin](https://opencomponents.dev/docs/getting-started/agent-plugin) , whose skills your agent picks up on its own. ::: :::accordion-item{label="Opening the URL in a browser brings me here"} That's expected. The server answers MCP clients, and sends browsers to this page. ::: :::accordion-item{label="My agent doesn't support MCP"} It can still read the standard. Every page of these docs is published as markdown, every contract as YAML, and `/llms.txt` lists them all, as [For agents](https://opencomponents.dev/docs/getting-started/introduction#for-agents) in the introduction explains. ::: :::accordion-item{label="Can I run the server myself?"} Yes. It's in the `mcp/` folder of our [repository](https://github.com/uxfront-com/open-components){rel=""nofollow""} , and `pnpm dev:mcp` serves it on your machine, at `http://localhost:3100/mcp` by default. Our [contributing guide](https://github.com/uxfront-com/open-components/blob/main/.github/CONTRIBUTING.md#the-mcp-server){rel=""nofollow""} covers how it's built. ::: :: Still stuck? [Open an issue](https://github.com/uxfront-com/open-components/issues/new/choose){rel=""nofollow""} with your client, its version and what you tried, and we'll help you connect. # Agent Plugin Our agent plugin gives your agent the standard in one install: skills that build and review components the way the standard asks, and our [MCP server](https://opencomponents.dev/docs/getting-started/mcp-server), which they read it from. It follows [Agent Plugins](https://agent-plugins.org){rel=""nofollow""}, the open format for packaging skills and MCP servers, so the same plugin works in every client that supports it. [Install it](https://opencomponents.dev/#install-it) shows you how. The MCP server on its own gives your agent the standard as tools, but your agent still has to know when to reach for them, and the server's prompts only run when you start them. Skills are instructions your agent picks up on its own when a task calls for them. Ask it to build a dialog, or to review your checkout page, and it reads the contract, checks the work against every rule and cites each one by its ID, without being told how. The plugin is in [`plugins/open-components`](https://github.com/uxfront-com/open-components/tree/main/plugins/open-components){rel=""nofollow""} in our repository. It's free, with nothing to sign in to. ## Install it Most clients install it from our repository in one or two commands, from the marketplace file at its root, which lists the plugin. Then start a new session, so your agent picks up the skills. ### Claude Code ```bash claude plugin marketplace add uxfront-com/open-components claude plugin install open-components@open-components ``` That installs it for you, in every project. In a session, run the same as slash commands: ```text /plugin marketplace add uxfront-com/open-components /plugin install open-components@open-components ``` Its skills then start with `/open-components:`, as in `/open-components:build-component`, and `/mcp` lists the server as `plugin:open-components:open-components`. ### Codex ```bash codex plugin marketplace add uxfront-com/open-components codex plugin add open-components@open-components ``` Or run `/plugins` in Codex and install it from the marketplace's tab. Run `/mcp` to check that the server is connected. ### GitHub Copilot In Copilot CLI: ```bash copilot plugin marketplace add uxfront-com/open-components copilot plugin install open-components@open-components ``` In a session, use the same slash commands as in [Claude Code](https://opencomponents.dev/#claude-code). For Copilot's cloud agent on github.com, add the marketplace and the plugin to `.github/copilot/settings.json` in your repository. VS Code reads it too, and recommends the plugin to everyone who opens the repository: ```json { "extraKnownMarketplaces": { "open-components": { "source": { "source": "github", "repo": "uxfront-com/open-components" } } }, "enabledPlugins": { "open-components@open-components": true } } ``` ### VS Code Run **Chat: Install Plugin From Source** from the Command Palette and enter `https://github.com/uxfront-com/open-components`. VS Code finds the plugin in the repository and installs it, after asking you to trust the source. You can also add our repository to your marketplaces in `settings.json`, then search for `@agentPlugins` in the Extensions view and click **Install**: ```json { "chat.plugins.marketplaces": ["uxfront-com/open-components"] } ``` ### Cursor In the Cursor CLI, add our marketplace, then install the plugin from `/plugin`: ```bash agent plugin marketplace add https://github.com/uxfront-com/open-components.git ``` In the editor, copy the plugin into your local plugins folder, then run **Developer: Reload Window**: ```bash git clone --depth 1 https://github.com/uxfront-com/open-components.git /tmp/open-components cp -R /tmp/open-components/plugins/open-components ~/.cursor/plugins/local/open-components ``` ### Kiro Kiro calls plugins powers. Open the **Powers** panel, choose **Add Custom Power**, then **Import power from GitHub**, and enter the plugin's folder: ```text https://github.com/uxfront-com/open-components/tree/main/plugins/open-components ``` ### Hermes Agent ```bash hermes plugins install uxfront-com/open-components/plugins/open-components --enable ``` That downloads only the plugin's folder. Run `hermes plugins list` to check that it's enabled. ### OpenClaw ```bash openclaw plugins install open-components --marketplace uxfront-com/open-components ``` Run `openclaw plugins inspect open-components` to check it, which shows its format as Agent Plugins. ### OpenHands Under **Plugins**, click **Add plugin**, set **Source** to `github:uxfront-com/open-components` and **Path** to `plugins/open-components`, then click **Install**. With the SDK, pass the same as a plugin source: ```python PluginSource(source="github:uxfront-com/open-components", repo_path="plugins/open-components") ``` ### Other clients - **Any client that supports Agent Plugins** can load the plugin from a folder: clone our repository and point it at `plugins/open-components`. NanoClaw, for one, only takes templates from a folder, so copy it to `templates/open-components`, then run: ```bash ncl groups create --template open-components --name "Open Components" ``` - **Clients that run Agent Skills but not plugins** can still have the skills. This installs them in Claude Code, Codex, Cursor, Gemini CLI and dozens of other agents, from `/.well-known/skills/` on this site: ```bash npx skills add https://opencomponents.dev ``` :brIt leaves out the MCP server, so [connect it](https://opencomponents.dev/docs/getting-started/mcp-server#connect-it) yourself, or let the skills read the standard from this site. ## What it offers ### Skills Your agent picks a skill when your request matches what it's for. In most clients, you can also start one yourself, as a slash command like `/build-component`. | Skill | What it's for | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `build-component` | Builds a component in your framework, from its contract, its reference implementation and its tests, or, for one on the [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap), following the Button's structure | | `review-component` | Reviews a component against its contract, or your styles against [Design Tokens](https://opencomponents.dev/docs/foundations/design-tokens), reporting every rule as pass or fail with its ID and the evidence, then fixes the failures | | `review-usage` | Does the same for a screen that uses a component, against the rules the screen meets, like keeping one primary button per view | | `adopt-token-paths` | Renames your CSS variables to [token paths](https://opencomponents.dev/docs/foundations/design-tokens), then adds the Stylelint rule that keeps them that way | They ask for what the MCP server's [prompts](https://opencomponents.dev/docs/getting-started/mcp-server#prompts) ask for, under the same names, then follow the steps the prompts point your agent at. ### The MCP server The plugin connects our MCP server, at `https://mcp.opencomponents.dev/mcp`, under the name `open-components`. The [MCP Server](https://opencomponents.dev/docs/getting-started/mcp-server#what-it-offers) page covers its tools, prompts and resources. If you've already added the server yourself, remove that entry once the plugin is installed, so your agent doesn't see every tool twice. Where a client doesn't connect the MCP servers in a plugin, or can't reach ours, the skills read the same contracts and pages from this site, at their [`/raw`](https://opencomponents.dev/docs/getting-started/introduction#for-agents) URLs. ## An example Once the plugin is installed, just ask: ```text Review our Button against Open Components. ``` Your agent picks up `review-component`, reads the Button's contract with `get-contract`, and lists the rules the component itself meets with `list-rules`. Then it reports every rule as pass or fail, with its ID and the evidence from your code, and fixes the failures. # Design Tokens Design Tokens are the named decisions behind every component, such as its colours, sizes, spacing and corner radii. In CSS, they're custom properties, and since their names are all that people, tools and agents have to go on, the names matter as much as the values. The biggest problem is that a name like `--blue-2` doesn't say what it's for, and `--color-primary-text` can be read in more than one way. Is it the `primary-text` colour, or the `text` of `color-primary`? This page covers how every Open Components token is named, a convention we call **token paths**. We'll look at: - **Token paths** - how to name a token, and why with a double dash - **Semantic names** - how to name a token after what it's for - **Theme tokens** - the colours that every component shares - **Component variables** - how a component names its own variables - **Checking tokens** - how linters and agents can hold your tokens to all of this If you'd rather be walked through it a step at a time, with names to rename and a whole component named from start to finish, read [How to name design tokens](https://opencomponents.dev/blog/how-to-name-design-tokens) on our blog. ## At a glance | Aspect | Tokens | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | Convention | Token paths, as in `--{group}--{name}` | | Separators | `--` between groups, and `-` between the words inside a group or a name | | Characters | Lowercase letters and digits | | Names | Semantic, saying what a token is for rather than what it looks like | | Theme | `--color--{color}`, `--color--{color}-contrast`, `--color--{color}-text` and `--color--focus` | | Components | `--{component}--{name}`, or `--{component}--{part}--{name}` for a part, set on the component's root | | Tools | `{color.primary}` in DTCG, `color/primary` in Figma and `color.primary` in [Styleframe](https://styleframe.dev){rel=""nofollow""} | | Lint | Stylelint's `custom-property-pattern` | ## Token paths A token's name is its path, made of the groups it belongs to, followed by its own name. Groups are separated by a double dash, and the words inside a group or a name by a single dash. ```css :root { --color--primary: …; /* color › primary */ --color--primary-contrast: …; /* color › primary-contrast */ --font-size--sm: …; /* font-size › sm */ } .button { --button--icon--size: 1rem; /* button › icon › size */ } ``` We call this convention token paths because the double dash plays the part of the dot in a path. The path stays the same wherever your tokens live, so moving between your design files, your token files and your CSS only means swapping the separator: | Where | How it's written | | -------------------- | ----------------------- | | CSS | `--color--primary-text` | | Design tokens (DTCG) | `{color.primary-text}` | | Figma variables | `color/primary-text` | | Styleframe | `color.primary-text` | ### Groups Most tokens only need two levels, the first saying what they belong to, and the second what they are. - The first group is the token's scope. It's either a category, like `color`, `spacing`, `font-size` or `border-radius`, or a component, like `button`. - The last part is the token's name, like `primary`, `md` or `height`. - A variation of a token stays in its name. The label on the primary fill is `--color--primary-contrast`, and a darker shade would be `--color--primary-shade-50`, rather than `--color--primary--contrast` or `--color--primary--shade-50`. When a token belongs to a part or a state of a component, rather than to the component as a whole, give that part or state a group of its own, even for a single token. The button sizes its icons with `--button--icon--size`, a tooltip's arrow would have `--tooltip--arrow--size`, and a link's hover state `--link--hover--color`. Since the group is there from the first token, adding a second one later, like `--button--icon--color`, never means renaming the first. A CSS property stays in one piece, though. `font-size` is a single name, so the button's text is sized with `--button--font-size`, rather than `--button--font--size`, and the same goes for names like `border-radius` and `line-height`. ### Why a double dash The double dash is what makes a name readable in both directions, by people and by tools. - **It's unambiguous.** With single dashes, `--font-size-sm` could be `font.size-sm`, `font-size.sm` or `font.size.sm`, and a tool has no way to tell which. `--font-size--sm` can only be `font-size.sm`, so tools, and agents, can turn any name back into its path. It's the same reason the [DTCG format](https://www.designtokens.org/tr/2025.10/format/){rel=""nofollow""} doesn't allow dots in token names. - **It's searchable.** Searching for `--button--` finds every variable of the button and nothing else, while `--button-` would also find a button group's `--button-group--gap`. - **It doesn't clash.** Tailwind CSS names its theme variables with single dashes, like `--color-blue-500` and `--radius-lg`, and libraries built on it add their own, like daisyUI's `--color-primary`. A token path can never have the same name as one of them, so your tokens and theirs can share a page. ## Semantic names Name a token after what it's for, rather than what it looks like. `--color--primary` still makes sense after a rebrand and in dark mode, while `--color--indigo-600` doesn't. It's the same idea as the Button's [`color`](https://opencomponents.dev/docs/components/button/ui#colours) [prop](https://opencomponents.dev/docs/components/button/ui#colours), which describes an intent rather than a hue. Tokens come in up to three tiers, and each tier reads from the one before it: | Tier | What it holds | For example | Read by | | --------- | ----------------------------- | ------------------------------------- | -------------- | | Palette | Every value you have | `--color--indigo-600`, `--spacing--4` | The theme | | Theme | What each value is for | `--color--primary`, `--color--focus` | Components | | Component | One component's own decisions | `--button--height`, `--button--fill` | That component | The palette is optional. Our reference tokens skip it, and set the theme straight from values in the Tailwind CSS palette. What matters is that components only read theme tokens, so a new brand or a dark mode is a new set of theme values, and no component has to change. ```css /* Do: the button reads what the colour is for */ .button[data-color="primary"] { --button--fill: var(--color--primary); } /* Don't: it reads a colour from the palette, so a new brand means editing every component */ .button[data-color="primary"] { --button--fill: var(--color--indigo-600); } ``` ## Theme tokens Every component reads its colours from the same theme tokens, so a single theme styles them all. There are three tokens per colour, plus a focus colour: | Token | What it is | | --------------------------- | ----------------------------------------------------- | | `--color--{color}` | The colour itself, for fills and tints | | `--color--{color}-contrast` | Text and icons on top of the fill | | `--color--{color}-text` | Text and icons in that colour, straight on the page | | `--color--focus` | The focus ring, which is the same for every component | `{color}` is one of `primary`, `secondary`, `neutral`, `success`, `info`, `warning` and `error`, the same colours as the `color` prop. A component with `color="primary"` reads `--color--primary`, `--color--primary-contrast` and `--color--primary-text`. Each pairing has to stay readable. `-contrast` needs a contrast of 4.5:1 against its colour, `-text` needs 4.5:1 against the page ([WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html){rel=""nofollow""}), and `--color--focus` needs 3:1 against the page ([WCAG 1.4.11](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html){rel=""nofollow""}), in both light and dark mode. Components that mix these colours, like the Button's `soft` variant, check their own pairings on top of that. The tokens use `light-dark()`, which follows `color-scheme`, so a single token holds the value for both modes: ```css :root { --color--primary: light-dark(oklch(51.1% 0.262 276.966), oklch(67.3% 0.182 276.935)); --color--primary-contrast: light-dark(oklch(100% 0 0), oklch(14.1% 0.005 285.823)); --color--primary-text: light-dark(oklch(45.7% 0.24 277.023), oklch(78.5% 0.115 274.713)); /* …secondary, neutral, success, info, warning and error */ --color--focus: light-dark(oklch(51.1% 0.262 276.966), oklch(67.3% 0.182 276.935)); } ``` You'll find the full set, with values that pass in both modes, in the Button's [`tokens.css`](https://opencomponents.dev/docs/components/button#reference-implementation). ## Component variables A component names its own variables after itself, as `--{component}--{name}`, or `--{component}--{part}--{name}` for one of its parts, and sets them on its root: ```css .button { --button--height: 2.25rem; --button--radius: 0.5rem; --button--icon--size: 1rem; --button--fill: var(--color--neutral); } .button[data-size="sm"] { --button--height: 2rem; --button--radius: 0.375rem; } .button[data-color="primary"] { --button--fill: var(--color--primary); } ``` - Setting them on the root, rather than on `:root`, keeps them with the component. Each size or colour changes them with a single selector, and nothing leaks into the rest of the page. - Starting them with the component's name makes it clear who owns them, so `--button--fill` can never be mistaken for a theme token. - Their colours come from the theme tokens, so the component follows every theme on its own. Some components draw a part the same way as another component, like the Combobox, which draws its panel, its options and its tags with the [Select](https://opencomponents.dev/docs/components/select)'s code. For those parts it reads the other component's variables, rather than a copy of its own, so one class restyles both and the two can't drift apart. Both roots set them, and the component's contract lists them under `shared`, apart from its own `variables`: ```css .select, .combobox { --select--option--radius: 0.25rem; --select--tag--height: 1.5rem; } .combobox { --combobox--empty--color: color-mix(in srgb, currentColor 70%, transparent); } ``` To tune a component, set its variables from a class of yours rather than with an inline style, since inline styles can't be reused, can't respond to media queries and are blocked by a strict Content Security Policy. Components put their styles in the `components` [cascade layer](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer){rel=""nofollow""}, and a style outside a layer beats a layered one whatever its specificity, so a single class is all it takes: ::framework-switcher #react ```tsx [GetStarted.tsx] import styles from "./GetStarted.module.css"; export function GetStarted() { return ( ); } ``` ```css [GetStarted.module.css] .pill { --button--radius: 999px; } ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-ts @Component({ selector: "app-get-started", imports: [Button], template: ``, styles: ` .pill { --button--radius: 999px; } `, }) export class GetStarted {} ``` #solid ```tsx [GetStarted.tsx] import styles from "./GetStarted.module.css"; export function GetStarted() { return ( ); } ``` ```css [GetStarted.module.css] .pill { --button--radius: 999px; } ``` #astro ```astro ``` #vanilla ```html ``` :: The layers follow the same order as Tailwind CSS (`theme`, `base`, `components` and `utilities`), so components win over its resets and give way to its utilities. Keep in mind that a reset of your own outside a layer, like `button { border-radius: 0 }`, would win too, so it's best to put your resets in the `base` layer. Every component page covers its own variables under Tokens, as the [Button](https://opencomponents.dev/docs/components/button/ui#tokens) does. ## Checking tokens The naming can be checked automatically, and agents can check the rest against the contract below. ### Lint Stylelint's [`custom-property-pattern`](https://stylelint.io/user-guide/rules/custom-property-pattern/){rel=""nofollow""} rule checks every custom property against a pattern, without its leading `--`. This one accepts token paths and nothing else: ```json [.stylelintrc.json] { "rules": { "custom-property-pattern": [ "^[a-z0-9]+(-[a-z0-9]+)*(--[a-z0-9]+(-[a-z0-9]+)*)+$", { "message": "Name CSS variables as token paths, like --color--primary" } ] } } ``` It flags `--color-primary`, `--button-height`, `--Color--primary`, `--color---primary` and `--primary`, and it checks `var()` references as well as declarations. That means it flags other libraries' variables too, like Tailwind's, so run it on your theme and your components' styles. ### Described Here's the whole convention in one block, for agents to read before they write or review a token: ```yaml convention: token-paths standard: https://opencomponents.dev/docs/foundations/design-tokens format: "--{group}--{name}" # "--{group}--{part or state}--{name}" for a part or state, even with one token separators: { group: "--", word: "-" } pattern: "^--[a-z0-9]+(-[a-z0-9]+)*(--[a-z0-9]+(-[a-z0-9]+)*)+$" paths: css: "--color--primary" dtcg: "{color.primary}" figma: color/primary styleframe: color.primary theme: colors: [primary, secondary, neutral, success, info, warning, error] tokens: ["--color--{color}", "--color--{color}-contrast", "--color--{color}-text", "--color--focus"] components: "--{component}--{name}, or --{component}--{part}--{name}, set on the component's root" overrides: "A class of yours, outside a layer. Components style themselves in @layer components, in Tailwind's layer order." rules: https://opencomponents.dev/docs/foundations/design-tokens#checklist ``` It's also published on its own at [`/raw/docs/foundations/design-tokens.yaml`](https://opencomponents.dev/raw/docs/foundations/design-tokens.yaml){external=""}, with every rule from the checklist in place of the `rules` link. ### Prompts You can point your agent straight at this page. To move your variables over to token paths, you could use: ```text Rename our CSS variables to follow the Open Components token paths: https://opencomponents.dev/raw/docs/foundations/design-tokens.md List our token groups first, then rename every variable along with every var() that reads it, keeping the values as they are. Then add the Stylelint rule from the page, and fix anything it reports. ``` And to review them: ```text Review our theme and component styles against the Open Components tokens standard: https://opencomponents.dev/raw/docs/foundations/design-tokens.md For each rule in its checklist, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` ## Checklist Here's every rule in one place, along with where it comes from and how to check it. Your tokens meet the standard when they meet every **must**, and each **should** is expected unless you have a good reason not to follow it. The basis says where a rule comes from. Contrast rests on **WCAG** 2.2, at level AA, while the naming rules are our own, marked **Open Components**, since WCAG has nothing to say about how you name your variables. | Rule | Level | Requirement | Basis | Check | | ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ---------------- | | `tokens/token-paths` | Must | Variables are named as token paths, in lowercase, with `-` between words and `--` between groups | Open Components | Stylelint | | `tokens/semantic-names` | Must | Theme and component tokens say what they're for, rather than what they look like | Open Components | Review | | `tokens/theme-only` | Must | Components read theme tokens, and never palette tokens or raw colours | Open Components | Review | | `tokens/shared-theme` | Must | Components read the shared theme tokens, so a single theme styles them all | Open Components | Review | | `tokens/component-scope` | Must | A component's own variables start with its name, like `--button--`, and are set on its root, and parts it shares with another component read that component's variables | Open Components | Review | | `tokens/class-overrides` | Should | Components put their styles in the `components` cascade layer, so a class can set their variables without an inline style | Open Components | Review | | `tokens/contrast` | Must | `-contrast` has 4.5:1 against its colour, `-text` 4.5:1 against the page and `--color--focus` 3:1, in light and dark mode | WCAG 1.4.3, 1.4.11 (AA) | Contrast checker | | `tokens/groups` | Should | A part or state always gets its own group, like `--button--icon--size`, while a variation or a CSS property stays in one name | Open Components | Review | ## FAQ ::accordion :::accordion-item{label="Isn't the double dash a BEM modifier?"} Not here. In BEM, `--` marks a modifier, as in `.button--primary` . Token paths use it the way a path uses a dot, so `--color--primary` reads as the `primary` token in the `color` group, rather than a colour modified to be primary. BEM names classes and token paths name variables, so the two can live side by side. ::: :::accordion-item{label="Can I use token paths with Tailwind CSS?"} Yes. Tailwind reads any variable you put in parentheses, as in `bg-(--color--primary)`. If you'd like shorter utilities, you can map your tokens onto its theme: ```css @theme inline { --color-primary: var(--color--primary); } ``` With that, `bg-primary` sets `background-color: var(--color--primary)`, so your tokens stay the single source of truth. ::: :::accordion-item{label="Why three tokens per colour?"} Because one colour can't be readable on both sides. `--color--warning` is a bright yellow, so the text on top of it has to be dark, and on a white page, warning text needs a much darker shade than the fill. With `-contrast` and `-text` , each pairing gets a colour that passes on its own, in both light and dark mode. ::: :::accordion-item{label="How do I move from single-dash names?"} One group at a time. A script can't tell where a single-dash name's group ends, which is exactly the problem token paths solve, so start by listing your groups, like `color` and `button`. Then replace `--color-` with `--color--`, and so on, in declarations and `var()` references alike. With Perl, for example: ```sh perl -pi -e 's/--(color|button)-(?=[a-z])/--$1--/g' $(git grep -lE -e '--(color|button)-[a-z]') ``` The Stylelint rule above will then catch anything you've missed. ::: :: ## Sources - [Design Tokens Format Module](https://www.designtokens.org/tr/2025.10/format/){rel=""nofollow""}, for token paths and groups - [CSS Custom Properties for Cascading Variables](https://www.w3.org/TR/css-variables-1/){rel=""nofollow""} - [Styleframe: Variables](https://www.styleframe.dev/docs/api/variables){rel=""nofollow""}, for the dot notation and its double-dash output - [Figma: Overview of variables, collections and modes](https://help.figma.com/hc/en-us/articles/14506821864087-Overview-of-variables-collections-and-modes){rel=""nofollow""} - [Material Design 3: Design tokens](https://m3.material.io/foundations/design-tokens/overview){rel=""nofollow""}, for the tiers - [Tailwind CSS: Theme variables](https://tailwindcss.com/docs/theme){rel=""nofollow""} - [Stylelint: custom-property-pattern](https://stylelint.io/user-guide/rules/custom-property-pattern/){rel=""nofollow""} - [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/){rel=""nofollow""} # User Interface (UI) Let's start with how a button looks: its parts, how much attention it asks for, what it means, how big it is and how it shows each of its states. ## Anatomy ::button-anatomy 1. **Container** — The ` ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` ::: :: | Variant | Looks | Use it for | | --------- | --------------------------- | ------------------------------------------------------------------ | | `solid` | Filled | The main action of a view, so there's only one per view or group | | `outline` | A border and no fill | Secondary actions next to a solid one | | `soft` | A tinted fill | Secondary actions that need a bit more presence, and dense layouts | | `subtle` | A tinted fill with a border | The same as `soft`, with an edge that holds up on busy backgrounds | | `ghost` | Nothing until you hover it | Tertiary actions in toolbars, table rows and icon-only buttons | | `link` | Underlined text | Low-emphasis actions that sit among text | Keep in mind that `link` is only a look. A button with `variant="link"` still runs an action, so if you want it to navigate, give it an `href` as well. It's underlined even at rest, because its colour alone isn't enough to tell it apart from the text around it ([WCAG 1.4.1](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html){rel=""nofollow""}), and we recommend thickening the underline on hover. ## Colours The `color` prop describes the intent behind an action rather than its hue. A name like `primary` will still make sense after a rebrand, while `blue` might not. The label is what carries the meaning, so people who can't tell the colours apart, or who browse with forced colours, still get the same message ([WCAG 1.4.1](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html){rel=""nofollow""}). ::inkline-example --- height: 267 example: button/ButtonColors title: Button colours --- :::framework-switcher #react ```tsx {/* Every colour works with every variant. */} ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx {/* Every colour works with every variant. */} ``` #astro ```astro ``` #vanilla ```html ``` ::: :: | Colour | Intent | For example | | ----------- | -------------------------------------------------------- | --------------------------- | | `primary` | The main action, in your brand colour | Save, Publish, Continue | | `secondary` | A second brand colour, for actions you want to set apart | Upgrade, Try Pro | | `neutral` | Everything else, and the default | Cancel, Back, Edit, Filter | | `success` | Completes something in a positive way | Approve, Mark as done | | `info` | Helps or explains something | Take the tour, Show details | | `warning` | Goes ahead despite a risk | Publish anyway, Override | | `error` | Destroys something, or can't be undone | Delete, Remove, Revoke | Note that `secondary` doesn't mean a secondary action, even though its name sounds like it. For a secondary action, it's best to lower the variant instead, for example with `variant="outline"` next to a `solid` primary button. Every colour reaches a contrast of 4.5:1 in every variant, at rest, on hover and when pressed, in both light and dark mode (you'll find the details under [tokens](https://opencomponents.dev/docs/components/button/ui#tokens)). ## Sizes The `size` prop scales the height, text, icons, padding and corner radius together, and `md` is the default. We recommend sticking to one size per region of the page, and changing it for the whole region rather than for individual buttons. ::inkline-example --- height: 134 example: button/ButtonSizes title: Button sizes --- :::framework-switcher #react ```tsx {/* …sm, md, lg, xl */} ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx {/* …sm, md, lg, xl */} ``` #vanilla ```html ``` ::: :: | Size | Min. height | Text | Icon | Padding | Gap | Radius | | ---- | ----------- | ---- | ---- | ------- | --- | ------ | | `xs` | 24px | 12px | 14px | 8px | 4px | 6px | | `sm` | 32px | 14px | 16px | 12px | 8px | 6px | | `md` | 36px | 14px | 16px | 16px | 8px | 8px | | `lg` | 40px | 16px | 20px | 20px | 8px | 8px | | `xl` | 48px | 16px | 20px | 24px | 8px | 12px | Sizes are set in `rem`, and the table shows the values we recommend, on a 4px grid, at the default text size of 16px. Every size meets the 24 × 24px minimum from [WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html){rel=""nofollow""}, except for a short `link` label inside a sentence, which WCAG allows. On touch screens, each one also gets a 44 × 44px hit area without looking any bigger. The heights are minimums, so the button grows with larger text or with a label that wraps. ## Icons Icons are there to support the label, and they should only replace it in the few icon-only buttons that everyone recognises. You can use any icon library you like (the examples use [Lucide](https://lucide.dev){rel=""nofollow""}'s, like `PlusIcon`) and place the icons in the `leading` and `trailing` slots. ::inkline-example{example="button/ButtonIcon" title="Buttons with icons"} :::framework-switcher #react ```tsx ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #vanilla ```html ``` ::: :: - A leading icon reinforces the action, like a plus for creating something or a bin for deleting it. A trailing icon hints at what comes next: a chevron opens a menu, an arrow moves you forward, and an arrow pointing out of a box takes you to another site. - Icons are decorative, so the slots wrap them in `aria-hidden="true"`. This way, screen readers announce the label once, instead of something like "plus icon, New project". - Only make a button icon-only when the icon is universally understood (think close, search, settings or more) and space is tight. The button still keeps its label, just visually hidden, because screen readers read it, voice control users say it out loud and agents use it to find the button. It's a good idea to show the label in a tooltip too. - In right-to-left layouts, remember to mirror the icons that point along the reading direction, such as arrows. ## States Each state has a look of its own, styled from the attribute that exposes it. That way, what people see and what assistive technologies report can never drift apart, and a button can't look disabled without actually being disabled. ::inkline-example{example="button/ButtonStates" title="Button states"} :::framework-switcher #react ```tsx ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` ::: :: | State | Selector | Recommended look | | -------- | ---------------------------------------- | ------------------------------------------------------ | | Hover | `:hover`, inside `@media (hover: hover)` | An 8% state layer | | Active | `:active` | A 12% state layer | | Focus | `:focus-visible` | A 2px outline, 2px from the edge, in `--color--focus` | | Disabled | `:disabled` or `[aria-disabled="true"]` | 50% opacity, a `not-allowed` cursor and no state layer | | Loading | `[data-loading]` | A spinner over the content and a `progress` cursor | | Pressed | `[aria-pressed="true"]` | A 12% state layer | | Expanded | `[aria-expanded="true"]` | A 12% state layer | For hover and press, we recommend state layers, which lay the label's own colour over the background at 8% and 12%, much like the [state layers](https://m3.material.io/foundations/interaction/states/state-layers){rel=""nofollow""} in Material Design. A single rule covers all 42 combinations of colour and variant, and it keeps contrast predictable, since the tokens still pass 4.5:1 with the layers applied. None of the states change the button's size or position, so there's no bolder label on hover and no border that appears on focus. A target that moves under your pointer is easy to miss. You'll find how each state behaves under [Every state](https://opencomponents.dev/docs/components/button/ux#every-state). ## Hierarchy and placement Try to keep a single primary action per view or group, and make it the only `solid` `primary` button. When every button competes for attention, none of them stands out. You can rank the rest with `variant`, using `outline` or `soft` for secondary actions and `ghost` or `link` for tertiary ones. ::inkline-example --- example: button/ButtonHierarchy title: Buttons ranked by emphasis --- :::framework-switcher #react ```tsx ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` ::: :: - Keep the order the same across your product. In our examples, the primary action comes last, where the eye ends up, which is on the right in left-to-right layouts and on the left in right-to-left ones. - Keep the DOM order and the visual order the same. Properties like `flex-direction: row-reverse` and `order` move buttons around visually but not for the keyboard, which then jumps around unexpectedly ([WCAG 1.3.2](https://www.w3.org/WAI/WCAG22/Understanding/meaningful-sequence.html){rel=""nofollow""}, [2.4.3](https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html){rel=""nofollow""}). - We recommend leaving at least 8px between buttons, so that a slightly missed tap doesn't land on the one next to it. - Size buttons to fit their label. On narrow screens, stack them in the same order, and they'll stretch to full width on their own inside a flex column. The width is up to the layout, which is why the Button doesn't have a prop for it. ## Tokens The button reads three [theme tokens](https://opencomponents.dev/docs/foundations/design-tokens#theme-tokens) per colour, plus one focus colour that every component shares: | Token | Used for | | --------------------------- | ------------------------------------------------------------------------------------ | | `--color--{color}` | The `solid` fill, and the tint of `soft` and `subtle` | | `--color--{color}-contrast` | The label and icons on top of the fill | | `--color--{color}-text` | The label and icons on the page, for `outline`, `soft`, `subtle`, `ghost` and `link` | | `--color--focus` | The focus ring, which is the same for every component | Everything else is derived from these. We recommend mixing 12% of the fill into the page for the `soft` variant, and the label colour into borders and state layers. Our reference tokens come from the Tailwind CSS palette and pass 4.5:1 for every colour and variant, at rest, on hover and when pressed, on both white and zinc-900. If you change them, make sure to check the same pairs. ```css :root { --color--primary: light-dark(oklch(51.1% 0.262 276.966), oklch(67.3% 0.182 276.935)); --color--primary-contrast: light-dark(oklch(100% 0 0), oklch(14.1% 0.005 285.823)); --color--primary-text: light-dark(oklch(45.7% 0.24 277.023), oklch(78.5% 0.115 274.713)); /* …secondary, neutral, success, info, warning and error */ --color--focus: light-dark(oklch(51.1% 0.262 276.966), oklch(67.3% 0.182 276.935)); } ``` If you need to tune a button, you can set its [own variables](https://opencomponents.dev/docs/foundations/design-tokens#component-variables), such as `--button--height`, `--button--padding` or `--button--radius`, from a class. The Button's styles sit in the `components` cascade layer, so your class wins without any specificity tricks: ::framework-switcher #react ```tsx [GetStarted.tsx] import styles from "./GetStarted.module.css"; export function GetStarted() { return ( ); } ``` ```css [GetStarted.module.css] .pill { --button--radius: 999px; } ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-ts @Component({ selector: "app-get-started", imports: [Button], template: ``, styles: ` .pill { --button--radius: 999px; } `, }) export class GetStarted {} ``` #solid ```tsx [GetStarted.tsx] import styles from "./GetStarted.module.css"; export function GetStarted() { return ( ); } ``` ```css [GetStarted.module.css] .pill { --button--radius: 999px; } ``` #astro ```astro ``` #vanilla ```html ``` :: ## UI Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------ | ------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------- | | `button/intent-colors` | Must | Both | Colours describe the action's intent rather than a hue, and never carry that meaning on their own | WCAG 1.4.1 (A), Open Components | Review | | `button/one-primary` | Should | Usage | There's one solid primary button per view or group, and the rest are ranked with `variant` | Open Components | Review | | `button/contrast` | Must | Component | The label has a contrast of 4.5:1 at rest, on hover and when pressed, in every variant, and the focus ring has 3:1 against the page | WCAG 1.4.3, 1.4.11 (AA) | axe `color-contrast` | | `button/link-underlined` | Must | Component | The `link` variant is underlined at rest, so it doesn't rely on colour alone to stand out from the text around it | Open Components, beyond WCAG 1.4.1 (A) | Review | | `button/focus-visible` | Must | Component | Keyboard focus shows an `outline` at least 2px thick, offset from the button, on `:focus-visible` | WCAG 2.4.7 (AA), 2.4.13 (AAA) | Keyboard | | `button/target-size` | Must | Component | The button is at least 24 × 24px, unless it's a `link` inside a sentence, with a 44 × 44px hit area on touch screens | WCAG 2.5.8 (AA), 2.5.5 (AAA) | axe `target-size` | | `button/resizable` | Must | Component | The button is sized with `min-height` and padding in `rem`, and its label wraps instead of being clipped or truncated | Open Components, beyond WCAG 1.4.4, 1.4.10, 1.4.12 (AA) | 200% zoom | | `button/stable-size` | Must | Component | No state changes the button's size or position | Open Components | Visual regression test | | `button/state-selectors` | Should | Component | States are styled from the attributes that expose them | Open Components | Review | | `button/hover-capable` | Should | Component | Hover styles only apply inside `@media (hover: hover)` | Open Components | Review | | `button/forced-colors` | Must | Component | The button's boundary, focus, disabled and pressed states stay visible in forced colours mode | Open Components | Emulation | | `button/more-contrast` | Should | Component | Borders are drawn at full strength when `prefers-contrast: more` is set | Open Components | Emulation | | `button/reduced-motion` | Must | Component | Nothing turns or slides when `prefers-reduced-motion: reduce` is set | WCAG 2.3.3 (AAA) | Emulation | ## FAQ ::accordion :::accordion-item{label="Should a button have a pointer cursor?"} Our reference implementation uses `cursor: pointer` , since that's the convention on the web and people read the hand as "this does something". Operating systems use the arrow for their own buttons, though, and some design systems follow them. Either choice is fine, as long as all your buttons agree. What matters more is the cursor over disabled ( `not-allowed` ) and loading ( `progress` ) buttons. ::: :: # User Experience (UX) Now let's look at how a button behaves for every person, input and setting. A good button is [accessible](https://opencomponents.dev/docs/components/button/ux#accessible), [predictable](https://opencomponents.dev/docs/components/button/ux#predictable), designed in [every state](https://opencomponents.dev/docs/components/button/ux#every-state) and [adaptive](https://opencomponents.dev/docs/components/button/ux#adaptive). ## Accessible ### Use the native element A native ` {/* Don't: there's no role, focus or keyboard support until you rebuild them */}
Save
``` #vue ```vue
Save
``` #svelte ```svelte
Save
``` #angular ```angular-html
Save
``` #solid ```tsx {/* Do: you get the role, focus, keyboard and disabled state for free */} {/* Don't: there's no role, focus or keyboard support until you rebuild them */}
Save
``` #astro ```astro
Save
``` #vanilla ```html
Save
``` :: ### Name every button The label is also the button's accessible name. Screen readers announce it, voice control users say it out loud ("click Save"), and tests and agents use it to find the button. - An icon-only button keeps its label, only visually hidden, through `label` and `iconOnly`. Hidden text is still ordinary text, so it gets translated along with the rest of the page, which translation tools don't always do for `aria-label`. - If you name a button with `aria-label` or `aria-labelledby`, make sure the name includes the visible label, ideally at the start ([WCAG 2.5.3](https://www.w3.org/WAI/WCAG22/Understanding/label-in-name.html){rel=""nofollow""}). A button that shows "Send" but is named "Submit message" won't respond when someone says "click Send". - If there's extra context, put it in a description, which screen readers read after the name. You can do that with `aria-describedby`, pointing at text like "Deleting is permanent". ### Contrast and size - The label needs a contrast of at least 4.5:1 with its background, in every variant and state ([WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html){rel=""nofollow""}), and the focus ring needs 3:1 against the page ([WCAG 1.4.11](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html){rel=""nofollow""}). Disabled buttons are exempt, but they should still be readable. - Every button is at least 24 × 24px ([WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html){rel=""nofollow""}). On touch screens, the hit area grows to 44 × 44px ([WCAG 2.5.5](https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced.html){rel=""nofollow""}), which is the size Apple recommends, while Material recommends 48dp. ### Show focus When you reach a button with the keyboard, it shows an outline in the same focus colour as every other component ([WCAG 2.4.7](https://www.w3.org/WAI/WCAG22/Understanding/focus-visible.html){rel=""nofollow""}). It needs to be at least 2px thick and drawn outside the button, and we recommend 2px for both. We use `:focus-visible`, so the ring appears for keyboard users but not on every click, and we draw it with `outline`, which survives forced colours mode where `box-shadow` doesn't. You'll also want to keep focused buttons clear of sticky headers and footers, which you can do with `scroll-padding` ([WCAG 2.4.11](https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html){rel=""nofollow""}, [2.4.12](https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-enhanced.html){rel=""nofollow""}). ### Don't nest interactive elements HTML doesn't allow links, buttons, inputs or `tabindex` inside a button, or a button inside a link. Keyboards and screen readers can't reliably reach the inner control, and a single click ends up activating both. If you'd like a whole card to be clickable, stretch its title link over the card with a pseudo-element, and lift the card's buttons above it. ## Predictable ### Run actions on click Always run your actions on `click`. It fires for the mouse, touch, pen, `Enter`, `Space` and assistive technologies, and only when the pointer is released, so people can still change their mind by moving away before letting go ([WCAG 2.5.2](https://www.w3.org/WAI/WCAG22/Understanding/pointer-cancellation.html){rel=""nofollow""}). Events like `mousedown`, `pointerdown` and `touchstart` fire as soon as you press, and never for the keyboard. ### Keyboard | Key | Button | Link (`href`) | | ------------------ | -------------------------- | ---------------- | | `Tab`, `Shift+Tab` | Moves focus to and from it | The same | | `Enter` | Activates it | Follows the link | | `Space` | Activates it, on release | Scrolls the page | A link that looks like a button still behaves like a link, because that's what keyboard and screen reader users expect from the role they hear. ### Move focus where people expect it After a button is activated, focus should go where the [APG](https://www.w3.org/WAI/ARIA/apg/patterns/button/){rel=""nofollow""} recommends: - A button that opens a dialog moves focus into it, and closing the dialog brings focus back to the button. - A button that acts in place, like Apply, keeps its focus. - A button that starts a new step moves focus to the start of that step. - A button that removes its own content, like Delete in a list, moves focus somewhere that makes sense, such as the next item. Focus should never fall back to the top of the page. ### Write labels that say what happens - Start with a verb and name the object, as in "Save changes", "Delete project" or "Invite member", rather than "OK", "Yes", "Submit" or "Click here". - Keep labels short. We recommend sentence case, without a full stop. - Add an ellipsis (…) when the action needs more input before it happens, like "Save as…" or "Schedule…". - Use the same label for the same action everywhere ([WCAG 3.2.4](https://www.w3.org/WAI/WCAG22/Understanding/consistent-identification.html){rel=""nofollow""}). ### Make destructive actions recoverable ::inkline-example --- example: button/ButtonDestructive title: A destructive button --- :::framework-switcher #react ```tsx ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` ::: :: - Use `color="error"` and name what's being destroyed, so "Delete project" rather than "Delete" or "Yes". - For everyday actions, offer undo rather than asking for confirmation. Save confirmations for what can't be undone, especially when data, money or legal commitments are involved ([WCAG 3.3.4](https://www.w3.org/WAI/WCAG22/Understanding/error-prevention-legal-financial-data.html){rel=""nofollow""}). - In a confirmation dialog, name both choices by their outcome, and don't give the destructive one the initial focus ([APG dialog](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/){rel=""nofollow""}). ### Don't submit forms by accident In HTML, a ` ``` #vue ```vue
``` #svelte ```svelte
``` #angular ```angular-html
``` #solid ```tsx
``` #astro ```astro
``` #vanilla ```html
``` :: ## Every state ### Disabled A disabled button can't be activated, and there are two ways to disable one: - `disabled` sets the native attribute. The button leaves the tab order, and screen readers announce it as dimmed or unavailable when they read through the page. - `disabled` with `focusableWhenDisabled` sets `aria-disabled="true"` instead. The button stays in the tab order, so keyboard and screen reader users can still find it, along with whatever explains why it's disabled, while the Button blocks activation on its own. Reach for `focusableWhenDisabled` whenever a button can be disabled while it has focus, like Next once you've paged to the end of a list. Native `disabled` would take its focus away and drop it on the ``, and keyboard and screen reader users would lose their place. For a button that's busy with its own action, use [`loading`](https://opencomponents.dev/docs/components/button/ux#loading) instead, which keeps its focus on its own. We recommend disabling as little as you can. A disabled Submit button doesn't tell anyone what's missing, so it's usually better to keep it enabled, validate on submit and move focus to the first error. When a button really has to be disabled, explain why next to it, or in a tooltip on a focusable disabled button. Also, avoid faking a disabled state with `pointer-events: none`. Clicks fall through to whatever is underneath, tooltips can't open, and the keyboard can still activate the button. ### Loading A loading button is busy with the action it was just asked to do. It keeps its focus, size and name, it can't be activated again, and it lets screen readers know that it's busy. ::inkline-example{example="button/ButtonLoading" title="A loading button"} :::framework-switcher #react ```tsx import { useState } from "react"; export function SaveChanges() { const [saving, setSaving] = useState(false); const [status, setStatus] = useState(""); async function save() { setSaving(true); try { await api.save(form); setStatus("Changes saved"); } catch { setStatus("Couldn't save your changes. Try again."); } finally { setSaving(false); } } return ( <>

{status}

); } ``` #vue ```vue ``` #svelte ```svelte

{status}

``` #angular ```angular-ts import { Component, signal } from "@angular/core"; @Component({ selector: "app-save-changes", imports: [Button], template: `

{{ status() }}

`, }) export class SaveChanges { saving = signal(false); status = signal(""); async save() { this.saving.set(true); try { await api.save(form); this.status.set("Changes saved"); } catch { this.status.set("Couldn't save your changes. Try again."); } finally { this.saving.set(false); } } } ``` #solid ```tsx import { createSignal } from "solid-js"; export function SaveChanges() { const [saving, setSaving] = createSignal(false); const [status, setStatus] = createSignal(""); async function save() { setSaving(true); try { await api.save(form); setStatus("Changes saved"); } catch { setStatus("Couldn't save your changes. Try again."); } finally { setSaving(false); } } return ( <>

{status()}

); } ``` #astro ```astro

``` #vanilla ```html

``` ::: :: - It keeps its focus, because loading sets `aria-disabled="true"` instead of `disabled`. Disabling a focused button takes its focus away (Chrome moves it back to the ``), and keyboard and screen reader users lose their place. - It keeps its size and name. The spinner covers the content, which stays in place but turns transparent, so nothing around the button moves and the accessible name stays the same. - It can't run twice. Clicks, `Enter` and `Space` are ignored until loading ends, and so is `Enter` in a form field when the button is the form's first submit button, which means no double submissions and no double charges. - It's announced. When loading starts, the Button announces its `loadingLabel` through a polite live region. Announcing the outcome is up to the page, with a status message like the one above, or an alert for errors ([WCAG 4.1.3](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html){rel=""nofollow""}). ### Toggle buttons A toggle button switches something on and off, and tells assistive technologies which one it is with `aria-pressed`. A screen reader would announce it as "Mute, toggle button, pressed". ::framework-switcher #react ```tsx ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` :: Keep the label the same in both states, so it says "Mute" whether it's pressed or not. If you'd rather change the label, like Play and Pause, leave `aria-pressed` out, since the label already tells people the state. For a setting that stays on or off, like "Email notifications", a [Switch](https://opencomponents.dev/docs/components/switch) is a better fit. ### Menu buttons A button that opens a menu says so with `aria-haspopup="menu"`, and uses `aria-expanded` to say whether the menu is open. We recommend a trailing chevron, which gives sighted users the same hint, while the menu itself takes care of the arrow keys and focus, as described in the [APG menu button](https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/){rel=""nofollow""} pattern. ::framework-switcher #react ```tsx ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` :: ## Adaptive ### Pointer, touch and pen - Hover styles only apply to pointers that can actually hover (`@media (hover: hover)`), otherwise a tap would leave the button looking hovered. - On touch screens, every button gets a hit area of at least 44 × 44px, drawn by an invisible `::before`, without changing how big it looks. - We recommend `touch-action: manipulation`, which stops a quick second tap from zooming the page, and a transparent `-webkit-tap-highlight-color`, which removes the grey flash on tap, since the button already draws its own pressed state. ### Motion When someone prefers reduced motion (`prefers-reduced-motion: reduce`), nothing turns or slides ([WCAG 2.3.3](https://www.w3.org/WAI/WCAG22/Understanding/animation-from-interactions.html){rel=""nofollow""}). We recommend letting the spinner pulse instead of turning, so it still shows that the button is busy, which the [Spinner](https://opencomponents.dev/docs/components/spinner/ux#motion) does on its own. ### More contrast When someone asks for more contrast (`prefers-contrast: more`), as with Increase contrast on macOS and iOS, the borders of `outline` and `subtle` buttons are drawn in the label's colour at full strength, rather than a tint of it. The labels already pass 4.5:1, so they stay as they are. ### Forced colours Windows contrast themes replace every colour with the user's own, and drop backgrounds, gradients and shadows. To stay visible, the Button keeps a transparent border, which the system draws as its outline, draws focus with `outline`, and marks its states with system colours. We recommend `GrayText` when it's disabled and `Highlight` when it's pressed or expanded. ### Colour scheme The tokens use `light-dark()`, which follows `color-scheme`, so the Button adapts to your light and dark themes on its own. We've checked the contrast in both. ### Text size and spacing Heights are minimums in `rem`, so the button grows with its text instead of clipping it. Labels wrap at 200% text size ([WCAG 1.4.4](https://www.w3.org/WAI/WCAG22/Understanding/resize-text.html){rel=""nofollow""}), with wider line, letter and word spacing ([WCAG 1.4.12](https://www.w3.org/WAI/WCAG22/Understanding/text-spacing.html){rel=""nofollow""}) and on screens as narrow as 320px ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html){rel=""nofollow""}). A button's label should never be truncated. ### Languages and direction The Button uses logical properties and `leading` and `trailing` slots rather than left and right, so it mirrors itself in right-to-left languages. Translated labels are often much longer than English ones, which is one more reason to never give a button a fixed width. Remember to translate `loadingLabel` along with your labels, and to mark a label in another language with `lang`, so that screen readers pronounce it correctly ([WCAG 3.1.2](https://www.w3.org/WAI/WCAG22/Understanding/language-of-parts.html){rel=""nofollow""}). ::inkline-example --- height: 111 example: button/ButtonLanguages title: Buttons in German and Arabic --- :::framework-switcher #react ```tsx
``` #vue ```vue
``` #svelte ```svelte
``` #angular ```angular-html
``` #solid ```tsx
``` #astro ```astro
``` #vanilla ```html
``` ::: :: The arrow above has a `flip-in-rtl` class, which mirrors it in right-to-left layouts. Give the same class to any other icon that points along the reading direction: ```css .flip-in-rtl:dir(rtl) { scale: -1 1; } ``` ## UX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | --------------------------- | ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------- | --------------------------------- | | `button/native-element` | Must | Component | It's a native `
``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html Read the introduction ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html Read the introduction ``` ::: :: ::framework-switcher #react ```tsx {/* Do: use a link for navigation, even when it looks like a button */} {/* Don't: this can't be opened in a new tab, and screen readers won't list it as a link */} ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html See pricing ``` #solid ```tsx {/* Do: use a link for navigation, even when it looks like a button */} {/* Don't: this can't be opened in a new tab, and screen readers won't list it as a link */} ``` #astro ```astro ``` #vanilla ```html See pricing ``` :: ::accordion :::accordion-item --- label: Why not disable the submit button until the form is valid? --- Because a disabled button can't explain itself. People don't know which field is wrong, keyboard users can't focus it to find out, and screen reader users might not find it at all. It's better to keep it enabled, validate on submit and move focus to the first error, with a message next to each field. ::: :::accordion-item{label="Why a visually hidden label rather than aria-label?"} Both give the button a name, but hidden text is ordinary text, so it gets translated along with the rest of the page. It's also a single mechanism for every button, whether it's icon-only or not. We'd only reach for `aria-label` when there's no other choice, and then make sure it includes the visible text. ::: :: # Developer Experience (DX) Next, let's look at how developers use the Button. It has one API, with the same names as every other component, and it's typed end to end. ::framework-switcher #react ```tsx import { Button } from "@/components/Button"; export function Settings() { return ( ); } ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-ts import { Component } from "@angular/core"; import { Button } from "./button"; @Component({ selector: "app-settings", imports: [Button], template: ``, }) export class Settings { save() { // … } } ``` #solid ```tsx import { Button } from "~/components/Button"; export function Settings() { return ( ); } ``` #astro ```astro --- import Button from "../components/Button.astro"; --- ``` #vanilla ```html ``` :: ## Consistent Once you've learned the Button's API, you already know most of every other component's. These names mean the same thing everywhere in Open Components: | Name | Kind | What it means | | --------------------- | ----- | ----------------------------------------- | | `variant` | Prop | The emphasis, from `solid` down to `link` | | `color` | Prop | The intent, from `primary` to `error` | | `size` | Prop | `xs`, `sm`, `md`, `lg` or `xl` | | `label` | Prop | The text content, when it's plain text | | `disabled` | Prop | The component can't be used | | `loading` | Prop | The component is busy with an action | | `leading`, `trailing` | Slots | Content before and after the main content | | `click` | Event | The component was activated | We recommend `variant="solid"`, `color="neutral"` and `size="md"` as the defaults, while `type` always defaults to `"button"`. We chose `neutral` so that a `primary` button is always a conscious decision, made once per view. ## Type-safe Props, events and slots are typed, so your editor can autocomplete them and your type checker (`tsc`, `vue-tsc`, `svelte-check`, `ngc` or `astro check`) catches mistakes like `variant="primary"`. | Prop | Type | Default | Description | | ----------------------- | -------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------------------------- | | `variant` | `"solid" | "outline" | "soft" | "subtle" | "ghost" | "link"` | `"solid"` | How much attention the button asks for | | `color` | `"primary" | "secondary" | "neutral" | "success" | "info" | "warning" | "error"` | `"neutral"` | What the action means | | `size` | `"xs" | "sm" | "md" | "lg" | "xl"` | `"md"` | How big the button is | | `label` | `string` | | The label, when it's plain text. The default slot takes precedence over it | | `iconOnly` | `boolean` | `false` | Shows only the leading icon, while the label still names the button | | `type` | `"button" | "submit" | "reset"` | `"button"` | The native button type | | `href` | `string` | | Renders a link that looks like a button | | `disabled` | `boolean` | `false` | Blocks activation | | `focusableWhenDisabled` | `boolean` | `false` | Keeps a disabled button in the tab order | | `loading` | `boolean` | `false` | Blocks activation and shows a spinner, while keeping focus and size | | `loadingLabel` | `string` | `"Loading"` | Announced to screen readers when loading starts | | Event | Payload | Description | | ------- | ------------ | ---------------------------------------------------------------------------- | | `click` | `MouseEvent` | Fires when the button is activated, but never while it's disabled or loading | | Slot | Description | | ---------- | ----------------------------------------------------------------------- | | `default` | The label | | `leading` | An icon before the label, which is also the icon of an icon-only button | | `trailing` | An icon after the label | We also export `ButtonProps`, which comes in handy for wrappers and data-driven UIs: ::framework-switcher #react ```ts import type { ButtonProps } from "@/components/Button"; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` #vue ```ts import type { ButtonProps } from "@/components/Button.vue"; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` #svelte ```ts import type { ButtonProps } from "$lib/components/Button.svelte"; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` #angular ```ts import type { ButtonProps } from "./button"; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` #solid ```ts import type { ButtonProps } from "~/components/Button"; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` #astro ```ts import type { ComponentProps } from "astro/types"; import Button from "../components/Button.astro"; type ButtonProps = ComponentProps; const actions: (ButtonProps & { id: string })[] = [ { id: "cancel", label: "Cancel", variant: "ghost" }, { id: "publish", label: "Publish", color: "primary" }, ]; ``` :: ## Composable The root element is the ` ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html ``` #solid ```tsx ``` #astro ```astro ``` #vanilla ```html ``` :: ### Links and routers Passing an `href` renders an ``. For links that go through your router, give the Button the link's `href` and your router's click handler, which leaves modified clicks, like `Ctrl`-click to open a new tab, to the browser. Routers that handle every link on the page only need the `href`: ::framework-switcher #react ```tsx import { useHref, useLinkClickHandler } from "react-router"; export function SettingsLink() { const href = useHref("/settings"); const navigate = useLinkClickHandler("/settings"); return ( ); } ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html Settings ``` #solid ```tsx {/* Solid Router handles every link on the page. */} ``` #astro ```astro ``` #vanilla ```html Settings ``` :: Since the Button doesn't know anything about your router, it works with any of them. ### With other components - Tooltips on icon-only buttons repeat the button's label. The hidden label is what names the button, and the tooltip simply shows that name. - A [Popover](https://opencomponents.dev/docs/components/popover) opens from a Button with `popovertarget` and `aria-haspopup="dialog"`, like the Filters button above, and keeps its `aria-expanded` in step with whether it's open. Menus set `aria-haspopup`, `aria-expanded` and `aria-controls` on the Button, which passes them straight through. - The loading spinner is a [Spinner](https://opencomponents.dev/docs/components/spinner). The Spinner draws itself, while the Button places it over the content, sizes it with `--button--icon--size` and announces `loadingLabel`, since the Spinner stays hidden from screen readers. - A group of buttons is simply a flex container with a gap. A toolbar, where the arrow keys move between buttons, is a separate pattern. ## Controllable The Button doesn't keep any state of its own. Every state is a prop or an attribute that you control, so all of them are always within reach: | State | How you control it | | -------- | ------------------------------------------------------------------------------------------------------------------- | | Disabled | `disabled`, and `focusableWhenDisabled` | | Loading | `loading`, set when the action starts (see [Loading](https://opencomponents.dev/docs/components/button/ux#loading)) | | Pressed | `aria-pressed`, bound to whether it's on | | Expanded | `aria-expanded`, bound to whether its popup is open | | Focus | A ref to its element, and `focus()` | ## DX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | -------------------------- | ------ | --------- | ----------------------------------------------------------------------------------------------------------------------- | --------------- | ---------- | | `button/shared-vocabulary` | Must | Component | It uses the shared names: `variant`, `color`, `size`, `label`, `disabled`, `loading`, `leading`, `trailing` and `click` | Open Components | Review | | `button/typed` | Must | Component | Props, events and slots are typed, with unions rather than `string` | Open Components | Type check | | `button/explicit-type` | Must | Both | `type` defaults to `"button"`, and submit buttons say `type="submit"` explicitly | Open Components | Unit test | | `button/root-element` | Must | Component | The root element is the button itself, so attributes, listeners and refs land on it | Open Components | Unit test | | `button/stateless` | Should | Component | Every state is a prop or an attribute that the parent controls | Open Components | Review | ## FAQ ::accordion :::accordion-item{label="Can I use ?"} You can, but its label lives in an attribute, so it can't hold icons or a spinner. A ` ``` And here's what it renders: ```html ``` - Props are mirrored as `data-*` attributes. `data-variant`, `data-color` and `data-size` are always there, while `data-icon-only` and `data-loading` only appear when they're set. - Parts are marked with `data-slot` and always come in the same order: `leading`, `label`, `trailing` and `spinner`, which is a [Spinner](https://opencomponents.dev/docs/components/spinner/ax#deterministic). - States change attributes, never elements. The focused element is never replaced, so both focus and the screen reader's position survive every state change. - There's nothing random or generated, like IDs or timestamps, so the markup is the same on the server, on the client and in every snapshot. - Icon-only is always a prop, and never guessed from the content. ## Verifiable Every rule in the checklist can be checked, and about half of them automatically. ### Unit tests Every rule that the checklist checks with a unit test has one in `Button.test.ts`, which you'll find under [Reference implementation](https://opencomponents.dev/docs/components/button#reference-implementation). We run them on every change to this page, so the code you see always passes them. ### In the browser In the browser, you can run [axe](https://github.com/dequelabs/axe-core){rel=""nofollow""} to check names, contrast, target size and nesting, and use an [ARIA snapshot](https://playwright.dev/docs/aria-snapshots){rel=""nofollow""} to check what agents will see: ```ts import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; test("the publish dialog's buttons", async ({ page }) => { await page.goto("/posts/new"); await expect(page.getByRole("dialog")).toMatchAriaSnapshot(` - button "Cancel" - button "Schedule…" - button "Publish post" `); const { violations } = await new AxeBuilder({ page }) .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]) .analyze(); expect(violations).toEqual([]); }); ``` Some things still need a human, so try the button with the keyboard alone, with a screen reader and at 200% zoom, and with forced colours, more contrast and reduced motion turned on. You can emulate all three in Chrome DevTools, under Rendering. ### During development Our reference implementation also warns you in the console as soon as a button renders without an accessible name, which is the most common button bug out there. ### Prompts You can point your agent straight at this page. To build a button, you could use: ::framework-switcher #react ```text Build a Button component for our React design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vue ```text Build a Button component for our Vue 3 design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #svelte ```text Build a Button component for our Svelte 5 design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #angular ```text Build a Button component for our Angular design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #solid ```text Build a Button component for our Solid design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #astro ```text Build a Button component for our Astro design system that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vanilla ```text Build a Button for our design system in plain HTML, CSS and JavaScript that meets the Open Components Button standard: https://opencomponents.dev/raw/docs/components/button.md Follow its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` :: To review one, the contract is enough: ```text Review our Button against the Open Components Button contract: https://opencomponents.dev/raw/docs/components/button.yaml For each rule with a component or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` And to review how a screen uses its buttons: ```text Review how our checkout page uses its buttons against the Open Components Button contract: https://opencomponents.dev/raw/docs/components/button.yaml For each rule with a usage or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` ## AX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | -------------------------- | ------ | --------- | ----------------------------------------------------------------------------------- | --------------- | --------- | | `button/role-and-name` | Must | Component | It can be found by its role and name alone, with `getByRole("button", { name })` | WCAG 4.1.2 (A) | Unit test | | `button/deterministic-dom` | Must | Component | The same props render the same markup, and states change attributes, never elements | Open Components | Unit test | | `button/data-attributes` | Should | Component | Props are mirrored as `data-*` attributes, and parts are marked with `data-slot` | Open Components | Unit test | | `button/dev-warnings` | Should | Component | It warns during development when a button has no accessible name | Open Components | Unit test | # Button Buttons let people act on what's in front of them, whether that's saving a form, sending a message, opening a dialog or deleting a file. They're the most common interactive component in any interface, and also the one we most often get wrong. Think of a `
` that you can't reach with the keyboard, a form that gets sent twice, or a spinner that throws your focus back to the top of the page. This page walks you through building one the right way. We'll look at: ::card-group :::card --- icon: i-lucide-palette title: User Interface (UI) to: https://opencomponents.dev/docs/components/button/ui --- How a button looks, from its parts, variants and colours to its sizes, icons, states and tokens. ::: :::card --- icon: i-lucide-user title: User Experience (UX) to: https://opencomponents.dev/docs/components/button/ux --- How a button behaves for every person, input and setting, so it's accessible, predictable, clear in every state and adaptive. ::: :::card --- icon: i-lucide-code-xml title: Developer Experience (DX) to: https://opencomponents.dev/docs/components/button/dx --- How developers use the Button, with one consistent, typed API that composes with links, routers and other components. ::: :::card --- icon: i-lucide-bot title: Agentic Experience (AX) to: https://opencomponents.dev/docs/components/button/ax --- How agents read, build and check a button, from its accessibility tree to its contract, its DOM and its tests. ::: :: ## At a glance The examples on this page run on the Button from [Inkline](https://inkline.io){rel=""nofollow""}, a UI library built to follow this standard, in the framework you pick, so feel free to try things out as you read. The code under each example comes in React, Vue, Svelte, Angular, Solid, Astro and Vanilla, written for a Button with the same API in each. Pick yours from the Framework select above the sidebar. Vanilla is plain HTML and JavaScript, so it writes out the markup from the [DOM contract](https://opencomponents.dev/docs/components/button/ax#deterministic). ::inkline-example --- controls: true height: 691 example: button/ButtonPlayground title: Button playground --- :: | Aspect | Button | | -------- | --------------------------------------------------------------------------------------------------- | | Element | `} footer="By Charles Babbage" >

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

``` #vue ```vue

Babbage's machine for working out tables of numbers, by the method of differences.

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

``` #svelte ```svelte

Babbage's machine for working out tables of numbers, by the method of differences.

{#snippet eyebrow()}Project{/snippet} {#snippet media()}{/snippet}

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

{#snippet actions()}{/snippet} {#snippet footer()}By Charles Babbage{/snippet}
``` #angular ```angular-html

Babbage's machine for working out tables of numbers, by the method of differences.

Project

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

By Charles Babbage
``` #solid ```tsx

Babbage's machine for working out tables of numbers, by the method of differences.

} actions={} footer="By Charles Babbage" >

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

``` #astro ```astro

Babbage's machine for working out tables of numbers, by the method of differences.

Project

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

By Charles Babbage
``` #vanilla ```html

Difference Engine

Babbage's machine for working out tables of numbers, by the method of differences.

Analytical Engine

Project

Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

By Charles Babbage
``` ::: :: - Keep the heading short, and make it the thing people are choosing between, like the project's name, so they can tell cards apart by their headings alone. - The eyebrow is for a word or two that sorts the card, like a category or a date. Anything longer belongs in the body, where it doesn't push the heading down. - An image that only illustrates the heading, like a product photo next to the product's name, has an empty `alt`, so screen readers skip it rather than read the name twice. You'll find more under [Describe the media](https://opencomponents.dev/docs/components/card/ux#describe-the-media). - Keep the body to a sentence or two. A card is a summary of a page, and people go to that page for the rest. - We recommend at most two actions, ranked like any other Buttons, with an `outline` or `ghost` Button rather than a `solid` one, so a page of cards doesn't fill up with primary actions. - The footer is for details about the card rather than about its subject, like who made it, when it was updated or how many comments it has. Its text is smaller and lighter than the body's, at 4.5:1 like the eyebrow, so it doesn't compete with the body. - The parts have no borders between them. A line between two of them is a separator, which you add only where it helps, like above a footer of links. Inside a card it's decorative, since the heading already marks the structure, so draw it with an empty element's border, or use ``, rather than a plain `
`, which screen readers announce. To run edge to edge, it takes the card's padding back with negative margins, like `margin-inline: calc(-1 * var(--card--padding))`. ## Layout A set of cards is a list, so put them in a `
    `, with each card as an `
  • ` (`as="li"`). Screen readers then say how many cards there are, and let people skip past the whole list. A grid that fits as many cards as there's room for, each at least a set width, works on every screen without a breakpoint: ::card-layout-example :::framework-switcher #react ```tsx
      {projects.map((project) => ( } actions={} >

      {project.summary}

      ))}
    ``` #vue ```vue

      {{ project.summary }}

    ``` #svelte ```svelte
      {#each projects as project (project.id)} {#snippet media()}{/snippet}

      {project.summary}

      {#snippet actions()}{/snippet}
      {/each}
    ``` #angular ```angular-html
      @for (project of projects; track project.id) {
    • {{ project.summary }}

    • }
    ``` #solid ```tsx
      {(project) => ( } actions={} >

      {project.summary}

      )}
    ``` #astro ```astro
      {projects.map((project) => (

      {project.summary}

      ))}
    ``` #vanilla ```html
    ``` ::: :: ```css .projects { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(16rem, 100%), 1fr)); gap: 1rem; margin: 0; padding: 0; list-style: none; } ``` - The `min(16rem, 100%)` lets a card get narrower than 16rem on a narrow screen rather than overflow it, so the page never scrolls sideways at 320px wide ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html){rel=""nofollow""}). - Cards in a row of a grid stretch to the same height, and the body takes the spare height, or the header in a card without a body, so the actions and the footers line up from card to card. - Keep the cards in the same order in the DOM as on screen, and don't reorder them with `order`, `row-reverse` or `grid-auto-flow: dense`. `Tab` follows the DOM, so a card that's moved on screen makes focus jump around ([WCAG 1.3.2](https://www.w3.org/WAI/WCAG22/Understanding/meaningful-sequence.html){rel=""nofollow""}, [2.4.3](https://www.w3.org/WAI/WCAG22/Understanding/focus-order.html){rel=""nofollow""}). - Safari has dropped the list role from lists with `list-style: none`, so VoiceOver doesn't say how many items there are. If that matters to you, add `role="list"` to the `
      `. ## States A card on its own has no states, since there's nothing to do with it. A card that's a link has two, hover and focus, and both come from its link, so they only ever show when pressing the card would follow it. ::card-states-example :::framework-switcher #react ```tsx

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #vue ```vue

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #svelte ```svelte

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #angular ```angular-html

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #solid ```tsx

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #astro ```astro

      A machine for working out tables of numbers.

      A general-purpose mechanical computer.

      ``` #vanilla ```html

      Difference Engine

      A machine for working out tables of numbers.

      ``` ::: :: | State | Selector | Recommended look | | ----- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------- | | Hover | `:has(a[href]:hover)` on the root, inside `@media (hover: hover)` | The border at 45% of the text colour, up from 20%, and the heading underlined | | Focus | `a[href]:focus-visible::after`, the link's pseudo-element | A 2px outline, 2px outside the card, in `--color--focus` | Both states read the link, rather than the card. That way, the card only looks hovered while the pointer is over the part of it that follows the link, and not over one of its actions, which shows its own hover instead. None of the states change the card's size or position, and you'll find how they behave under [Every state](https://opencomponents.dev/docs/components/card/ux#every-state). ## Tokens The card reads two [theme tokens](https://opencomponents.dev/docs/foundations/design-tokens#theme-tokens), which every component shares: | Token | Used for | | ----------------------- | ---------------------------------------------------------------------------------------- | | `--color--neutral-text` | The text, and mixed into the border, the eyebrow, the footer and the media's placeholder | | `--color--focus` | The focus ring, which is the same for every component | Everything else is mixed from the text colour: 70% for the eyebrow and the footer, which need 4.5:1, and 20% for the border at rest and 45% on hover. With our reference tokens, from the Tailwind CSS palette, the eyebrow and the footer come to 5.6:1 on white and 7.4:1 on zinc-900, the same as the Input's placeholder. The border is lighter than the Input's, since a card's heading says what it is, and WCAG only asks for 3:1 on a boundary people need to see to find the component ([WCAG 1.4.11](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html){rel=""nofollow""}). You'll find the tokens themselves in the Button's [`tokens.css`](https://opencomponents.dev/docs/components/button#reference-implementation), which you can copy into your theme. If you need to tune a card, you can set its [own variables](https://opencomponents.dev/docs/foundations/design-tokens#component-variables), such as `--card--padding`, `--card--background` or `--card--media--aspect-ratio`, from a class. The Card's styles sit in the `components` cascade layer, so your class wins without any specificity tricks: ::framework-switcher #react ```tsx [ProjectCard.tsx] import styles from "./ProjectCard.module.css"; }>

      A general-purpose mechanical computer.

      ``` ```css [ProjectCard.module.css] .project { --card--background: var(--color--neutral-surface); --card--media--aspect-ratio: 4 / 3; } ``` #vue ```vue [ProjectCard.vue] ``` #svelte ```svelte [ProjectCard.svelte] {#snippet media()}{/snippet}

      A general-purpose mechanical computer.

      ``` #angular ```angular-ts [project-card.component.ts] @Component({ selector: "app-project-card", imports: [Card], template: `

      A general-purpose mechanical computer.

      `, styles: ` .project { --card--background: var(--color--neutral-surface); --card--media--aspect-ratio: 4 / 3; } `, }) export class ProjectCard {} ``` #solid ```tsx [ProjectCard.tsx] import styles from "./ProjectCard.module.css"; }>

      A general-purpose mechanical computer.

      ``` ```css [ProjectCard.module.css] .project { --card--background: var(--color--neutral-surface); --card--media--aspect-ratio: 4 / 3; } ``` #astro ```astro [ProjectCard.astro]

      A general-purpose mechanical computer.

      ``` #vanilla ```html

      Analytical Engine

      A general-purpose mechanical computer.

      ``` :: `--color--neutral-surface` stands in for a surface colour from your own theme, since the theme tokens don't have one. The Card is transparent by default, so it sits on whatever's behind it. If you give it a background, check the text's contrast against that background rather than the page's. ## UI Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ----------------------- | ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | -------------------------------------- | | `card/contrast` | Must | Component | The text, the eyebrow and the footer included, has a contrast of 4.5:1 against the card, and the focus ring has 3:1 against the page | WCAG 1.4.3, 1.4.11 (AA) | axe `color-contrast`, contrast checker | | `card/text-below-media` | Should | Component | Text sits below the media rather than on top of it, so its contrast doesn't depend on the image | Open Components | Review | | `card/focus-visible` | Must | Component | When its link has keyboard focus, an `outline` at least 2px thick shows around the whole card, outside its border | WCAG 2.4.7 (AA), 2.4.13 (AAA) | Keyboard | | `card/resizable` | Must | Component | Nothing in the card has a fixed height, so it grows with its text, and long words wrap instead of overflowing it | Open Components, beyond WCAG 1.4.4, 1.4.12 (AA) | 200% zoom | | `card/stable-size` | Must | Component | No state changes the card's size or position | Open Components | Visual regression test | | `card/media-ratio` | Should | Component | The media keeps its space with an aspect ratio, so cards line up and the page doesn't jump as images load | Open Components | Visual regression test | | `card/state-selectors` | Should | Component | Hover and focus are styled from the link, so the card only looks interactive where pressing it follows the link | Open Components | Review | | `card/hover-capable` | Should | Component | Hover styles only apply inside `@media (hover: hover)` | Open Components | Review | | `card/forced-colors` | Must | Component | The border and the focus ring stay visible in forced colours mode | Open Components | Emulation | | `card/more-contrast` | Should | Component | The border is drawn at full strength when `prefers-contrast: more` is set | Open Components | Emulation | | `card/reduced-motion` | Must | Usage | Nothing moves on hover or focus when `prefers-reduced-motion: reduce` is set | WCAG 2.3.3 (AAA) | Emulation | | `card/reflow` | Must | Usage | Cards in a grid get narrower rather than overflow, so the page never scrolls sideways at 320px wide | WCAG 1.4.10 (AA) | Emulation | | `card/quiet-actions` | Should | Usage | There are at most two actions, neither of them a `solid` Button | Open Components | Review | ## FAQ ::accordion :::accordion-item{label="Can a card have a shadow?"} Of course, from a class, if that suits your design. Keep the border too, though, even a faint one, since forced colours modes drop shadows, and a card drawn with a shadow alone would lose its edge in them. ::: :: # User Experience (UX) Now let's look at how a card behaves for every person, input and setting. A good card is [accessible](https://opencomponents.dev/docs/components/card/ux#accessible), [predictable](https://opencomponents.dev/docs/components/card/ux#predictable), designed in [every state](https://opencomponents.dev/docs/components/card/ux#every-state) and [adaptive](https://opencomponents.dev/docs/components/card/ux#adaptive). ## Accessible ### Use the right element The Card renders an `
      ` by default, which HTML defines as a self-contained piece of a page, one you could take out and still make sense of, like a project, a product or a post. That's what most cards are. The `as` prop picks another element when a card isn't one of those: | Element | `as` | When | | ----------- | ----------- | ------------------------------------------------------------------------------------- | | `
      ` | The default | The card stands on its own, like a project or a product | | `
    • ` | `"li"` | The card is one of a list, inside a `
        ` or an `
          ` | | `
          ` | `"section"` | The card is a part of the page, like a settings panel, rather than a thing of its own | | `
          ` | `"div"` | The card is only a box, and its content says everything | We recommend never making the card itself a link or a button. A card holds a heading, text and sometimes actions of its own, and a link or a button can't hold any of them well: its whole content becomes its name, and it can't have another link or button inside it. When the whole card should take people somewhere, its heading holds the link, as under [Make the heading the link](https://opencomponents.dev/docs/components/card/ux#make-the-heading-the-link). ### Give every card a heading The heading is how people find a card. Most screen reader users look for what they need on a page by moving from heading to heading, according to every [WebAIM Screen Reader User Survey](https://webaim.org/projects/screenreadersurvey10/){rel=""nofollow""}, and the heading is what they hear first when they land on a card. It's also what sighted people read first, and what tests and agents look for. - Every card has a heading that says what it's about, like the project's name ([WCAG 1.3.1](https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html){rel=""nofollow""}, [2.4.6](https://www.w3.org/WAI/WCAG22/Understanding/headings-and-labels.html){rel=""nofollow""}). The Card renders it as an `

          ` to `

          `, so it's a heading for assistive technologies too, rather than bold text. - Pick the level that fits the page's outline, with `headingLevel`. Cards in a section titled with an `

          ` get an `

          `, which is the default, while cards right under the page's `

          ` get an `

          `. A level that skips one, like an `

          ` under an `

          `, makes people wonder what they missed. - Give each card in a list a different heading, so people can tell them apart when they list the page's headings or links. ### Make the heading the link When the whole card takes people somewhere, like a project's page, put the link in the heading, around the heading's text, and stretch it over the card. `href` does that for you. The link is still just the heading's text, so it's named by the heading alone, while a pseudo-element of the link covers the whole card, so pressing anywhere on the card follows it. ::card-link-example :::framework-switcher #react ```tsx } actions={ <> } footer="By Charles Babbage" >

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          ``` #vue ```vue

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          ``` #svelte ```svelte {#snippet eyebrow()}Project{/snippet} {#snippet media()}{/snippet}

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          {#snippet actions()} {/snippet} {#snippet footer()}By Charles Babbage{/snippet}
          ``` #angular ```angular-html
          Project

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          By Charles Babbage
          ``` #solid ```tsx } actions={ <> } footer="By Charles Babbage" >

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          ``` #astro ```astro Project

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          By Charles Babbage
          ``` #vanilla ```html

          Charles Babbage's design for a general-purpose mechanical computer, first described in 1837.

          By Charles Babbage
          ``` ::: :: - The link's name is the heading, like "Analytical Engine", so screen readers announce a short name that says where it goes, and voice control users can say "click Analytical Engine" ([WCAG 2.4.4](https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html){rel=""nofollow""}, [2.5.3](https://www.w3.org/WAI/WCAG22/Understanding/label-in-name.html){rel=""nofollow""}). Wrapping the whole card in an `` would make all of its text the link's name, read out every time someone tabs to it. - It's a real ``, so it works like every other link. People can open it in a new tab with `Ctrl` or `Cmd`, or with the middle mouse button, copy its address, and see where it goes before they press it. A card with a click handler or `role="link"` loses all of that, and keyboard users can't reach it at all unless it has a `tabindex`. - Actions, like Save, stay outside the link, in `actions`, and sit above the stretched link, so pressing one runs it rather than following the link. `Tab` reaches them right after the link. HTML doesn't allow a button inside a link, which is one more reason the card itself is never the link. - A link inside the body or the eyebrow, like a link to the project's author, sits above the stretched link too, so it goes where it says. Keep them few, though, since a card with many links in it is harder to press in the right place. ### Describe the media An image that only illustrates the heading, like a photo of the product it names, gets an empty `alt=""`, which tells screen readers to skip it. If its alt text repeated the heading, people would hear the same thing twice. An image that shows something the text doesn't, like a chart or a floor plan, needs alt text that says what it shows ([WCAG 1.1.1](https://www.w3.org/WAI/WCAG22/Understanding/non-text-content.html){rel=""nofollow""}). ### Contrast and size - The text needs a contrast of at least 4.5:1 with the card's background, and so do the eyebrow and the footer, since people need to read them too ([WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html){rel=""nofollow""}). Text over an image is hard to keep at 4.5:1, which is why the Card puts its text below the media rather than on top of it. - The border doesn't need 3:1, since it doesn't tell people anything the heading doesn't ([WCAG 1.4.11](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html){rel=""nofollow""}). The focus ring does, against the page. - A card that's a link is a large target already, since the whole card follows the link. Its actions are Buttons, which are at least 24 × 24px ([WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html){rel=""nofollow""}), with a hit area of 44 × 44px on touch screens. Leave a gap between them, as the actions do, so a finger doesn't press the one next to it. ### Show focus When a card's link has focus, the whole card shows an outline in the same focus colour as every other component ([WCAG 2.4.7](https://www.w3.org/WAI/WCAG22/Understanding/focus-visible.html){rel=""nofollow""}). It's drawn by the link's pseudo-element, which covers the card, so it goes around the whole card rather than the heading's text, which is where people can press. Like the Button's, it's at least 2px thick and drawn outside the border, and we recommend 2px for both. An action shows its own focus ring instead, so only one thing on the page ever looks focused. You'll also want to keep focused cards clear of sticky headers and footers, which you can do with `scroll-padding` ([WCAG 2.4.11](https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html){rel=""nofollow""}, [2.4.12](https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-enhanced.html){rel=""nofollow""}). ## Predictable ### Keyboard | Key | Card | | ------------------ | ------------------------------------------------------------------------- | | `Tab`, `Shift+Tab` | Moves focus to the card's link, if it has one, and then on to its actions | | `Enter` | Follows the link | A card has no keys of its own. It's a link and some Buttons, which `Tab` reaches in the order they come in, like on the rest of the page. We recommend not adding arrow keys to move between cards, since people don't expect them on a list of links, and they'd have to find out that they work. A list where the arrow keys do move between items, like a feed that loads more as people scroll, is a pattern of its own, which the APG calls a [Feed](https://www.w3.org/WAI/ARIA/apg/patterns/feed/){rel=""nofollow""}. ### Put the heading first The heading comes first in the card's DOM, before the eyebrow and the media, while CSS shows the media and the eyebrow above it. People who move from heading to heading land at the start of the card, and hear what it's about before anything else. With an eyebrow or an image before the heading in the DOM, they'd land past them, and miss them. Moving content around with CSS is only safe for content people can't focus. `Tab` follows the DOM, so if the media held a link or a button, focus would go to the heading's link first and then jump back up to the media. Keep the media an image, and put anything people can press in the body, the actions or the footer. ### Write headings that say where they go When a card is a link, its heading is the link's name, so it's best to write it like one: the name of the thing the card is about, rather than "Read more" or "Learn more". People who list the links on a page see the names alone, and five links called "Read more" don't say where any of them go ([WCAG 2.4.4](https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html){rel=""nofollow""}). For the same reason, we recommend not adding a separate "Read more" link next to the stretched one, which would only be a second way to the same place. ### Don't nest interactive elements The link holds the heading's text and nothing else. HTML doesn't allow a link or a button inside a link, so nothing defines what browsers and screen readers should do with one. Actions go in `actions`, which is outside the link, and the stretched link only covers them on screen, where the Card lifts them above it. ## Every state ### Linked A card that's a link shows that it is when people point at it or tab to it. On hover, its border gets stronger and its heading is underlined, which tells people the whole card does something before they press it. On focus, it shows its focus ring. The pointer over the card is the link's own, so people see the hand they'd see over any other link. ### With actions A card can have actions of its own, like Save or Share, whether it's a link or not. They're Buttons, so they keep their names, their states and their focus rings, and pressing one runs it, even on a card that's a link. Once an action has done something, like saving the project, its state shows on the Button, like `aria-pressed` on a Save toggle, rather than on the card. ### Without media Not every card has an image, and an image can fail to load. The media keeps its space whatever its image does, with `aspect-ratio`, so cards in a row stay lined up, and the page doesn't jump when an image arrives late. While it loads, or if it fails, the space shows a faint tint of the text colour instead of a gap. If some cards in a list have no image at all, leave the media out of them, rather than showing an empty box. ### Loading While cards load, hold their place with placeholders the same size as the cards, so the page doesn't jump around when they arrive. A Skeleton, on our [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap), will do that for you. If the cards load because of something people did, like a search, say how many arrived in a status message, since a screen reader user won't see them appear. ### Long content Headings and text wrap rather than being cut off, and the card grows to fit them. We recommend not cutting headings off with an ellipsis or a line clamp. People can't read the rest, a screen reader still reads all of it, so the two disagree, and a translated heading is often longer than the original. ## Adaptive ### Pointer, touch and pen - Hover styles only apply to pointers that can actually hover (`@media (hover: hover)`), otherwise a tap would leave the card looking hovered. - On touch screens, the whole card follows its link, so it's an easy target, while its actions are Buttons with hit areas of their own, at least 44 × 44px. - The stretched link covers the card's text, so pressing and dragging on it drags the link rather than selecting the text. If people need to copy something from a card, like a code or an address, put it on the page the card links to, or leave that card without a link. ### Motion The Card doesn't move. If you'd like a card to lift or grow on hover, wrap the animation in `@media (prefers-reduced-motion: no-preference)`, so it only runs for people who haven't asked for less motion ([WCAG 2.3.3](https://www.w3.org/WAI/WCAG22/Understanding/animation-from-interactions.html){rel=""nofollow""}). Keep in mind that a card that grows can cover the ones next to it. ### More contrast When someone asks for more contrast (`prefers-contrast: more`), as with Increase contrast on macOS and iOS, the border is drawn in the text colour at full strength, rather than at 20%. The text, the eyebrow and the footer already pass 4.5:1, so they stay as they are. ### Forced colours Windows contrast themes replace every colour with the user's own, and drop backgrounds and shadows. The Card's border stays, since the system draws it in a colour of its own, focus is drawn with `outline`, in `Highlight`, and the media's `` keeps its image. That's why the Card draws its boundary with a border rather than a shadow, which these themes would drop. ### Colour scheme The tokens use `light-dark()`, which follows `color-scheme`, so the Card adapts to your light and dark themes on its own. If you give it a background, use a token that does the same, and check the text against it in both. ### Text size and spacing Nothing in the Card has a fixed height, so it grows with its text instead of clipping it, at 200% text size ([WCAG 1.4.4](https://www.w3.org/WAI/WCAG22/Understanding/resize-text.html){rel=""nofollow""}) and with wider line, letter and word spacing ([WCAG 1.4.12](https://www.w3.org/WAI/WCAG22/Understanding/text-spacing.html){rel=""nofollow""}). Long words, like a web address, wrap rather than overflow the card. Only the media keeps its shape, since it's sized by its width and its aspect ratio. ### Languages and direction The Card uses logical properties, so it mirrors itself in right-to-left languages, with its actions starting from the right: ::card-languages-example :::framework-switcher #react ```tsx } actions={} >

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` #vue ```vue

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` #svelte ```svelte {#snippet eyebrow()}مشروع{/snippet} {#snippet media()}{/snippet}

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          {#snippet actions()}{/snippet}
          ``` #angular ```angular-html
          مشروع

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` #solid ```tsx } actions={} >

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` #astro ```astro مشروع

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` #vanilla ```html

          تصميم تشارلز باباج لحاسوب ميكانيكي عام الغرض، وُصف لأول مرة عام 1837.

          ``` ::: :: - In right-to-left layouts, it's usually the page that sets `dir` and `lang`, on ``, and the Card follows it. Set them on a card when its language differs from the page's, like one card in a list of translations ([WCAG 3.1.2](https://www.w3.org/WAI/WCAG22/Understanding/language-of-parts.html){rel=""nofollow""}). - Images don't mirror themselves, which is usually right, since a photo flipped left to right looks wrong. Only flip an image that points along the reading direction, like an arrow. ## UX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------- | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------- | | `card/semantic-element` | Must | Component | It's an `
          ` by default, or a `
          `, `
          ` or `
        1. ` with `as`, and never a link or a button | Open Components, beyond WCAG 1.3.1 (A) | Unit test | | `card/list-of-cards` | Should | Usage | A set of cards is a list, with each card an `
        2. ` | WCAG 1.3.1 (A) | Review | | `card/heading` | Must | Both | Every card has a heading that says what it's about, at the level that fits the page's outline | WCAG 1.3.1 (A), 2.4.6 (AA) | Unit test, review | | `card/heading-first` | Should | Component | The heading comes first in the DOM, and the media and the eyebrow are shown above it with CSS alone | Open Components | Unit test | | `card/stretched-link` | Must | Component | A card that's a link has one link, in its heading, stretched over the card with a pseudo-element, and never a wrapping ``, `role="link"` or a click handler on the card | Open Components, beyond WCAG 2.1.1, 4.1.2 (A) | Unit test | | `card/link-name` | Must | Component | The link is named by the heading alone | WCAG 2.4.4 (A) | Unit test | | `card/link-purpose` | Should | Usage | Headings say where the link goes, differ from card to card, and there's no separate "Read more" link | WCAG 2.4.4 (A), 2.4.9 (AAA) | Review | | `card/actions-above` | Must | Component | Actions and other links in the card sit outside the stretched link and above it, so pressing one runs it | Open Components | Unit test, review | | `card/no-nesting` | Must | Both | The link holds the heading's text alone, with nothing interactive inside it | HTML | Unit test | | `card/keyboard` | Must | Component | `Tab` reaches the card's link once and then its actions, and `Enter` follows the link | WCAG 2.1.1, 2.4.3 (A) | Unit test | | `card/media-alt` | Must | Usage | An image that only illustrates the heading has `alt=""`, and one that shows more has alt text that says what | WCAG 1.1.1 (A) | axe `image-alt`, review | | `card/static-media` | Must | Usage | The media holds nothing people can focus, since it's shown above the heading but comes after it in the DOM | WCAG 1.3.2, 2.4.3 (A) | Keyboard | | `card/dom-order` | Must | Usage | Cards come in the same order in the DOM as on screen, without `order`, `row-reverse` or a `dense` grid | Open Components, beyond WCAG 1.3.2, 2.4.3 (A) | Keyboard | | `card/focus-not-obscured` | Must | Usage | Sticky headers and footers never cover a focused card, for example thanks to `scroll-padding` | WCAG 2.4.11 (AA), 2.4.12 (AAA) | Keyboard | | `card/no-truncation` | Should | Usage | Headings aren't cut off with an ellipsis or a line clamp | Open Components | Review | | `card/announce-results` | Should | Usage | Cards that load after something people did, like a search, are announced with a status message | WCAG 4.1.3 (AA) | Screen reader | | `card/mirrors-in-rtl` | Should | Component | It uses logical properties, so it mirrors itself in right-to-left layouts | Open Components | Review | ## FAQ ### Card or something else? A card summarises one thing, so people can scan a few of them and pick one. For anything else, another component will do a better job: | When people need to… | Use | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | Scan a few things and pick one, like projects or products | Cards, in a list | | Compare many things by their details, like prices and dates | Table | | Pick one option, like a plan, as part of a form | Radio Group, which can look like a set of cards | | Be told something important, like an error | Alert | | Read through a stream that loads more as they scroll | A list of cards, built on the APG's [Feed](https://www.w3.org/WAI/ARIA/apg/patterns/feed/){rel=""nofollow""} pattern | The Table, the Radio Group and the Alert are on our [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap). ::accordion :::accordion-item{label="Why not wrap the whole card in a link?"} Because a link's name is all of its text. A screen reader would read the whole card every time someone tabs to it, and voice control users would have to say all of it to press it. A link can't hold a button either, so a card wrapped in one can't have actions of its own. A link in the heading, stretched over the card, is pressed the same way, and named by the heading alone. ::: :::accordion-item{label="Can people select the text in a card that's a link?"} Not by dragging across it, since the stretched link covers it, and dragging a link drags its address. That's the trade-off for a whole card people can press. Keep text people might copy, like a code or an address, on the page the card links to, or leave that card without a link. Making the card a link with a click handler wouldn't help either, since it would trade the selection for everything a real link does. ::: :::accordion-item{label="Should a card's link open in a new tab?"} No more than any other link. Links that open new tabs on their own take people away from the page they were on, and break the back button. People who want a new tab can open one with `Ctrl` or `Cmd` , or the middle mouse button, which is one of the things a real link gives them. ::: :: # Developer Experience (DX) Next, let's look at how developers use the Card. It has one API, with the same names as every other component, it's typed end to end, and it needs no script at all, since everything it does is HTML and CSS. ::framework-switcher #react ```tsx import { Card } from "@/components/Card"; export function Projects({ projects }: { projects: Project[] }) { return ( <>

          Projects

            {projects.map((project) => (

            {project.summary}

            ))}
          ); } ``` #vue ```vue ``` #svelte ```svelte

          Projects

            {#each projects as project (project.id)}

            {project.summary}

            {/each}
          ``` #angular ```angular-ts import { Component, input } from "@angular/core"; import { Card } from "./card"; @Component({ selector: "app-projects", imports: [Card], template: `

          Projects

            @for (project of projects(); track project.id) {
          • {{ project.summary }}

          • }
          `, }) export class Projects { projects = input.required(); } ``` #solid ```tsx import { For } from "solid-js"; import { Card } from "~/components/Card"; export function Projects(props: { projects: Project[] }) { return ( <>

          Projects

            {(project) => (

            {project.summary}

            )}
          ); } ``` #astro ```astro --- import Card from "../components/Card.astro"; const { projects } = Astro.props; ---

          Projects

            {projects.map((project) => (

            {project.summary}

            ))}
          ``` #vanilla ```html

          Projects

          ``` :: ## Consistent Once you've learned the [Button](https://opencomponents.dev/docs/components/button/dx#consistent)'s and the [Input](https://opencomponents.dev/docs/components/input/dx#consistent)'s APIs, you already know the Card's `href` and `actions`. These names mean the same thing everywhere in Open Components: | Name | Kind | What it means | | --------- | ---- | --------------------------------------------------------- | | `href` | Prop | The component is a link, and this is where it goes | | `default` | Slot | The main content, between the component's tags | | `actions` | Slot | Buttons that act on the component, after its main content | The rest of the Card's names are its own, and each one says what it is: - `heading` is the heading, and `headingLevel` its level. We didn't call it `title`, which is an HTML attribute that shows a tooltip, so in Angular, Astro or plain HTML, where an attribute stays on the element, every card would grow one. `label` is for controls, which a card isn't. - `as` picks the element, as it does in many component libraries. We recommend `article` as the default, since it's what most cards are. - `media`, `eyebrow` and `footer` are named after the parts they fill, so the slot and the `data-slot` it renders have the same name. The Card also leaves a few props out, on purpose: - There's no `variant` or `color`. A card has no intent of its own, unlike a Button, and its look comes from its variables, which you set from a class. - There's no `disabled`. A card isn't a control, so there's nothing to disable. If its link isn't available, like a project that's been archived, leave out the `href` and say why in the body. - There's no `selected`. A card people pick, like a plan, is a choice, so it belongs to a form control: a Radio Group, on our [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap), when people pick one, or a [Checkbox Group](https://opencomponents.dev/docs/components/checkbox-group) when they pick any number, each with the keyboard and the states that a choice needs. - There's no `onClick`. The Card never listens for clicks, since its link does that job, and its actions are Buttons with listeners of their own. ## Type-safe Props and slots are typed, so your editor can autocomplete them and your type checker (`tsc`, `vue-tsc`, `svelte-check`, `ngc` or `astro check`) catches mistakes like `headingLevel={1}`, which would give a card the page's own heading level. | Prop | Type | Default | Description | | -------------- | -------------------------------------- | ----------- | ---------------------------------------------------------------------- | | `as` | `"article" | "section" | "div" | "li"` | `"article"` | The element it renders | | `heading` | `string` | | The heading, when it's plain text. The `heading` slot takes precedence | | `headingLevel` | `2 | 3 | 4 | 5 | 6` | `3` | The heading's level, which fits the page's outline | | `href` | `string` | | Links the card through its heading, stretched over the whole card | The Card doesn't fire events of its own. Its link and its actions fire theirs, like `click`, which you listen to on them. | Slot | Description | | --------- | ------------------------------------------------------------------------------------------ | | `default` | The body, like a sentence or two and some details | | `heading` | The heading, when it's more than plain text, or your router's link, which is stretched too | | `eyebrow` | A short line shown above the heading, like a category, which comes after it in the DOM | | `media` | An image, shown at the top, which comes after the heading in the DOM | | `actions` | Buttons that act on the card, like Save, which sit above the stretched link | | `footer` | A last line of details about the card, like who made it or when | We also export `CardProps`, which comes in handy for wrappers and data-driven pages: ::framework-switcher #react ```ts import type { CardProps } from "@/components/Card"; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` #vue ```ts import type { CardProps } from "@/components/Card.vue"; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` #svelte ```ts import type { CardProps } from "$lib/components/Card.svelte"; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` #angular ```ts import type { CardProps } from "./card"; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` #solid ```ts import type { CardProps } from "~/components/Card"; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` #astro ```ts import type { ComponentProps } from "astro/types"; import Card from "../components/Card.astro"; type CardProps = ComponentProps; const featured: CardProps = { heading: "Analytical Engine", headingLevel: 2, href: "/projects/analytical-engine" }; ``` :: ## Composable The root element is the card itself, the `
          ` or whichever element `as` picks, so everything you pass lands directly on it. That includes classes, styles, `id`, `dir`, `lang`, ARIA attributes and event listeners. A ref to the Card reaches that same element, so there's no wrapper to reach through. If you'd like an `
          ` to have a name of its own, give the heading's text an `id`, through the `heading` slot, and point the card's `aria-labelledby` at it. Keep in mind that a `
          ` with a name becomes a region landmark, which people can jump to, so only name a `section` card when it's one of the main parts of the page. ### Links and routers `href` renders a plain ``. For links that go through your router, put your router's link in the `heading` slot instead, and the Card stretches it over the card just the same, since it stretches any link in its heading. Routers that handle every link on the page only need the `href`: ::framework-switcher #react ```tsx import { Link } from "react-router"; Analytical Engine}>

          A general-purpose mechanical computer.

          ``` #vue ```vue

          A general-purpose mechanical computer.

          ``` #svelte ```svelte

          A general-purpose mechanical computer.

          ``` #angular ```angular-html
          ``` #solid ```tsx import { A } from "@solidjs/router"; Analytical Engine}>

          A general-purpose mechanical computer.

          ``` #astro ```astro

          A general-purpose mechanical computer.

          ``` #vanilla ```html ``` :: Since the Card doesn't know anything about your router, it works with any of them. ### With other components - Actions are [Buttons](https://opencomponents.dev/docs/components/button), which keep their names, states and focus rings, and sit above the stretched link. We recommend `sm` Buttons, ranked `outline` or `ghost`, so a page of cards doesn't fill up with primary actions. - A [Spinner](https://opencomponents.dev/docs/components/spinner) doesn't belong in a card while it loads. A Skeleton, on our [Roadmap](https://opencomponents.dev/docs/getting-started/roadmap), will hold the card's shape instead. - A Badge, also on our Roadmap, fits in the eyebrow, to mark a status like "New". - A card that opens a Dialog rather than a page gets a Button for it in `actions`, rather than a stretched link, since a link should always go somewhere. ## Controllable The Card doesn't keep any state of its own. Everything about it is a prop, an attribute or an element that you control: | What | How you control it | | ------------- | ------------------------------------------------------------------- | | Element | `as` | | Heading level | `headingLevel` | | Link | `href`, or a link in the `heading` slot | | Hover, focus | The browser, from the link | | Focus | The link's own `focus()`, through a ref to the card or to your link | ## DX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------- | ------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------- | | `card/shared-vocabulary` | Must | Component | It takes `href` like the Button and `actions` like the Input, and names its other slots after its parts: `heading`, `eyebrow`, `media` and `footer` | Open Components | Review | | `card/no-attribute-names` | Should | Component | No prop shares its name with an HTML attribute that does something else, like `title` | Open Components | Review | | `card/typed` | Must | Component | Props and slots are typed, with unions rather than `string` or `number`, so `headingLevel` only takes 2 to 6 | Open Components | Type check | | `card/root-element` | Must | Component | The root element is the card itself, so attributes, listeners and refs land on it | Open Components | Unit test | | `card/router-links` | Should | Component | A link in the `heading` slot, like a router's, is stretched over the card like the one `href` renders | Open Components | Unit test, review | | `card/stateless` | Should | Component | It keeps no state of its own | Open Components | Review | ## FAQ ::accordion :::accordion-item{label="Does the Card work before JavaScript loads?"} Yes, completely. Everything it does is HTML and CSS, so the server renders a real `
          ` , a real heading and a real link, which work before the page hydrates, and even without JavaScript at all. Only your actions, like Save, wait for your script. ::: :: # Agentic Experience (AX) Finally, let's look at how agents read, build and check a card. They rely on the same accessibility tree as assistive technologies, and on a contract they can check the code against. ## Semantic Agents that drive a browser, through Playwright or a browser MCP server, read the page through its accessibility tree, which is made of roles, names and states. This is how they see the cards under [Layout](https://opencomponents.dev/docs/components/card/ui#layout): ```yaml - list: - listitem: - heading "Analytical Engine" [level=3]: - link "Analytical Engine": - /url: /projects/analytical-engine - paragraph: A general-purpose mechanical computer, first described in 1837. - button "Save" - listitem: - heading "Difference Engine" [level=3]: - link "Difference Engine": - /url: /projects/difference-engine - paragraph: A machine for working out tables of numbers. - button "Save" ``` The images are left out, since their `alt` is empty. A card that's a `
          ` with a click handler shows up as a heading and some text, with nothing to say that pressing it does anything, so an agent can't follow it any more than a keyboard user can. With a real link, named by the heading, an agent can find the card and follow it, or find one of its actions: ```ts await page.getByRole("link", { name: "Analytical Engine" }).click(); const card = page.getByRole("listitem").filter({ has: page.getByRole("heading", { name: "Analytical Engine" }) }); await card.getByRole("button", { name: "Save" }).click(); ``` ## Described Here's the whole contract in one block, for agents to read before they build or review a card: ```yaml component: Card summary: Groups what people need to know about one thing, like a project or a product, under a heading. With an href, its heading is a link stretched over the whole card. standard: https://opencomponents.dev/docs/components/card element: article # or section, div or li, with as role: article # listitem as an li. A section is a region only once it has a name props: as: { type: [article, section, div, li], default: article } heading: { type: string } # the heading slot takes precedence headingLevel: { type: [2, 3, 4, 5, 6], default: 3 } href: { type: string } # links the card through its heading slots: default: The body, like a sentence or two and some details. heading: The heading, when it's more than plain text, or a router's link, which is stretched too. eyebrow: A short line shown above the heading, like a category, which comes after it in the DOM. media: An image, shown at the top, which comes after the heading in the DOM. actions: Buttons that act on the card, like Save, which sit above the stretched link. footer: A last line of details about the card, like who made it or when. states: hover: ":has(> [data-slot=header] > [data-slot=heading] a[href]:hover), in @media (hover: hover)" focus: "[data-slot=heading] a[href]:focus-visible, drawn around the card by its ::after" keyboard: Tab: Moves focus to the card's link, then to its actions. Enter: Follows the link. parts: [header, heading, link, eyebrow, media, body, actions, footer] # data-slot, in this order. The link is in the heading tokens: theme: ["--color--neutral-text", "--color--focus"] variables: [--card--padding, --card--gap, --card--radius, --card--border-color, --card--background, --card--media--aspect-ratio] layer: components # in Tailwind's order: theme, base, components, utilities rules: https://opencomponents.dev/docs/components/card#checklist ``` It's also published on its own at [`/raw/docs/components/card.yaml`](https://opencomponents.dev/raw/docs/components/card.yaml){external=""}, with every rule from the checklist in place of the `rules` link. It's a fraction of this page's length, so it's the one to give agents that only need the rules, and not the reasoning behind them. Every rule has a stable ID, like `card/stretched-link`, so you and your agents can cite it in reviews and commits. ## Deterministic The same props always render the same markup, leaving out anything your framework adds for itself, like comments or scoping attributes. For example, here's a card in a list, that links to a project: ```html

          A general-purpose mechanical computer.

          ``` And here's what it renders: ```html
        3. A general-purpose mechanical computer.

        4. ``` - The element is always the one `as` names, and the heading's level always the one `headingLevel` names, so neither is guessed from where the card is on the page. - Parts are marked with `data-slot` and always come in the same order: the `header`, which holds the `heading`, its `link` and the `eyebrow`, then the `media`, the `body`, the `actions` and the `footer`. Only the header and the heading are always there, and the others render when they're given. - Hover and focus are styles, never changes to the markup, so focus and the screen reader's position survive both. - There's nothing random or generated, like IDs or timestamps, so the markup is the same on the server, on the client and in every snapshot. ## Verifiable Every rule in the checklist can be checked, and about a third of them automatically. ### Unit tests Every rule that the checklist checks with a unit test has one in `Card.test.ts`, which you'll find under [Reference implementation](https://opencomponents.dev/docs/components/card#reference-implementation). We run them on every change to this page, so the code you see always passes them. ### In the browser Unit tests run without a layout, so they can't press the card's text and check that the stretched link catches it. In the browser, you can press the card the way people would, check that its actions don't follow the link, and run [axe](https://github.com/dequelabs/axe-core){rel=""nofollow""} to check contrast, alt text and the list: ```ts import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; test("a project card saves from its actions, and follows its link from anywhere else", async ({ page }) => { await page.goto("/projects"); const card = page.getByRole("listitem").filter({ has: page.getByRole("heading", { name: "Analytical Engine" }) }); await card.getByRole("button", { name: "Save" }).click(); await expect(page).toHaveURL(/\/projects$/); const { violations } = await new AxeBuilder({ page }) .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]) .analyze(); expect(violations).toEqual([]); // The middle of the card is its body text, which the stretched link covers. await card.click(); await expect(page).toHaveURL(/\/projects\/analytical-engine$/); }); ``` Some things still need a human, so try your cards with the keyboard alone, with a screen reader, where you can list the page's headings and links, on a phone, and at 200% zoom, with forced colours and more contrast turned on. You can emulate the last two in Chrome DevTools, under Rendering. ### Prompts You can point your agent straight at this page. To build a card, you could use: ::framework-switcher #react ```text Build a Card component for our React design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vue ```text Build a Card component for our Vue 3 design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #svelte ```text Build a Card component for our Svelte 5 design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #angular ```text Build a Card component for our Angular design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #solid ```text Build a Card component for our Solid design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #astro ```text Build a Card component for our Astro design system that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vanilla ```text Build a Card for our design system in plain HTML, CSS and JavaScript that meets the Open Components Card standard: https://opencomponents.dev/raw/docs/components/card.md Follow its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` :: To review one, the contract is enough: ```text Review our Card against the Open Components Card contract: https://opencomponents.dev/raw/docs/components/card.yaml For each rule with a component or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` And to review how a screen uses its cards: ```text Review how our projects page uses its cards against the Open Components Card contract: https://opencomponents.dev/raw/docs/components/card.yaml For each rule with a usage or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` ## AX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------ | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------- | | `card/role-and-name` | Must | Component | It can be found by its heading, with `getByRole("heading", { name })`, and a card that's a link by `getByRole("link", { name })` | WCAG 4.1.2 (A) | Unit test | | `card/deterministic-dom` | Must | Component | The same props render the same markup, with no generated IDs, and parts only render when they're given | Open Components | Unit test | | `card/data-attributes` | Should | Component | Parts are marked with `data-slot` | Open Components | Unit test | # Card Cards group what people need to know about one thing, like a project, a product or a person, so they can scan a page of them and pick one. They look like a box with a picture in it, which is why they're so often built with only a mouse in mind. Think of a card wrapped in a link, which a screen reader reads out from its first word to its last as the link's name, a `
          ` with a click handler, which keyboard users can't reach at all, or a Save button nested inside that link, which HTML doesn't allow. This page walks you through building one the right way. We'll look at: ::card-group :::card --- icon: i-lucide-palette title: User Interface (UI) to: https://opencomponents.dev/docs/components/card/ui --- How a card looks, from its parts and what goes in each of them to how cards sit together, its states and its tokens. ::: :::card --- icon: i-lucide-user title: User Experience (UX) to: https://opencomponents.dev/docs/components/card/ux --- How a card behaves for every person, input and setting, so it's accessible, predictable, clear in every state and adaptive. ::: :::card --- icon: i-lucide-code-xml title: Developer Experience (DX) to: https://opencomponents.dev/docs/components/card/dx --- How developers use the Card, with one consistent, typed API that composes with links, routers and other components, and needs no script. ::: :::card --- icon: i-lucide-bot title: Agentic Experience (AX) to: https://opencomponents.dev/docs/components/card/ax --- How agents read, build and check a card, from its accessibility tree to its contract, its DOM and its tests. ::: :: ## At a glance Every example on this page runs on our [reference implementation](https://opencomponents.dev/docs/components/card#reference-implementation), which does its part of every rule in the [checklist](https://opencomponents.dev/docs/components/card#checklist), so feel free to tab through them as you read. The code under each example comes in React, Vue, Svelte, Angular, Solid, Astro and Vanilla, written for a Card with the same API in each. Pick yours from the Framework select above the sidebar. Vanilla is plain HTML and JavaScript, so it writes out the markup from the [DOM contract](https://opencomponents.dev/docs/components/card/ax#deterministic). A card is a container rather than a control, so most of what it does comes from the elements in it: a heading, a link when the whole card takes you somewhere, and [Buttons](https://opencomponents.dev/docs/components/button) for anything else people can do with it. :card-playground | Aspect | Card | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Element | `
          `, or a `
          `, `
          ` or `
        5. ` with `as` | | Role | `article`, or `listitem` as an `
        6. ` | | Name | Its heading, which also names its link when the card is one | | Keyboard | `Tab` to its link, then to its actions, and `Enter` to follow the link | | States | Hover and focus, when it's a link | | Parts | Media, a header with the heading and an eyebrow, body, actions and footer, of which only the header and its heading are always there | | Pattern | None in the APG, since an [`
          `](https://html.spec.whatwg.org/multipage/sections.html#the-article-element){rel=""nofollow""} and a link cover it | | WCAG 2.2 | 1.1.1, 1.3.1, 1.3.2, 1.4.3, 1.4.11, 2.1.1, 2.4.4, 2.4.6, 2.4.7 and 4.1.2, among others | ## Checklist Here's every rule in one place, along with where it comes from and how to check it. A card meets the standard when it meets every **must**, and each **should** is expected unless you have a good reason not to follow it. The scope says who meets a rule. **Component** rules are met by the Card itself, so they're the ones to check when you build or review one. **Usage** rules are met by the pages that use it, like describing its images, so they're the ones to check when you review a screen. **Both** rules need the two to work together, like its heading: the Card renders one at the level you give it, as long as you give it a heading that says what the card is about. The basis says where a rule comes from. About half the rules rest on **WCAG** 2.2, which we follow at level AA, and name the success criteria behind them, and one comes from **HTML**. The rest are **Open Components** rules, which are our own, like putting the heading first in the DOM. Where a rule goes further than WCAG asks at level AA, its basis says so: some come from level **AAA**, like keeping cards still for people who ask for less motion, and a rule that asks for more than its criterion says **beyond**, like the stretched link, where WCAG would let a card be a link in other ways. You'll find the rules for each layer on its page: - [User Interface (UI) Checklist](https://opencomponents.dev/docs/components/card/ui#ui-checklist) - [User Experience (UX) Checklist](https://opencomponents.dev/docs/components/card/ux#ux-checklist) - [Developer Experience (DX) Checklist](https://opencomponents.dev/docs/components/card/dx#dx-checklist) - [Agentic Experience (AX) Checklist](https://opencomponents.dev/docs/components/card/ax#ax-checklist) ## Reference implementation Our Vue 3 reference implementation does its part of every rule on this page, and powers every example on it. Feel free to copy it into your design system and change how it looks, but try to keep how it behaves. It reads the same theme tokens as the Button, so copy [`tokens.css`](https://opencomponents.dev/docs/components/button#reference-implementation) from the Button's reference implementation into your theme too, and its examples put [Buttons](https://opencomponents.dev/docs/components/button#reference-implementation) in `actions`. The tests are in `Card.test.ts`. To run them, you'll need [Vitest](https://vitest.dev){rel=""nofollow""}, set to `environment: "jsdom"` and `globals: true`, along with `@testing-library/vue`, `@testing-library/user-event` and `@testing-library/jest-dom`. ::code-collapse :::code-group ```vue [Card.vue] ``` ```ts [Card.test.ts] import { render, screen, within } from "@testing-library/vue"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { h, ref } from "vue"; import Card from "./Card.vue"; const image = () => h("img", { src: "engine.png", alt: "" }); const button = (name: string, onClick?: () => void) => h("button", { type: "button", onClick }, name); describe("Card", () => { it("is an article, found by its heading", () => { render(Card, { props: { heading: "Analytical Engine" }, slots: { default: () => "A mechanical computer." } }); const card = screen.getByRole("article"); expect(within(card).getByRole("heading", { name: "Analytical Engine" })).toBeInTheDocument(); expect(card).toHaveTextContent("A mechanical computer."); }); it("renders a section, a div or a list item with as", () => { const { container } = render({ render: () => [ h(Card, { as: "section", heading: "Section" }), h(Card, { as: "div", heading: "Div" }), h("ul", [h(Card, { as: "li", heading: "List item" })]), ], }); expect(container.querySelector("section.card")).toBeInTheDocument(); expect(container.querySelector("div.card")).toBeInTheDocument(); expect(screen.getByRole("listitem")).toHaveClass("card"); expect(screen.queryByRole("article")).not.toBeInTheDocument(); }); it("has a heading at the level it's given, and level 3 by default", () => { render({ render: () => [h(Card, { heading: "Default" }), h(Card, { heading: "Second", headingLevel: 2 })], }); expect(screen.getByRole("heading", { name: "Default" })).toHaveProperty("tagName", "H3"); expect(screen.getByRole("heading", { name: "Second", level: 2 })).toBeInTheDocument(); }); it("puts its heading first, before its eyebrow and media, whatever the order on screen", () => { const { container } = render(Card, { props: { heading: "Analytical Engine" }, slots: { eyebrow: () => "Project", media: image, default: () => "A mechanical computer." }, }); const text = [...container.querySelectorAll("[data-slot='heading'], [data-slot='eyebrow'], img")]; expect(text.map((element) => element.getAttribute("data-slot") ?? element.tagName)).toEqual(["heading", "eyebrow", "IMG"]); }); it("links through its heading alone, without wrapping the card in a link or listening for clicks on it", () => { // Testing Library may listen on the root of whatever it renders, so the card's click // listeners are compared with those on a plain
          rendered the same way. const listen = vi.spyOn(Element.prototype, "addEventListener"); const clicks = (root: Element) => listen.mock.calls.filter(([type], i) => type === "click" && listen.mock.contexts[i] === root).length; const plain = render({ render: () => h("article") }).container.firstElementChild!; const { container } = render(Card, { props: { heading: "Analytical Engine", href: "/projects/analytical-engine" }, slots: { eyebrow: () => "Project", default: () => "A mechanical computer." }, }); expect(clicks(container.firstElementChild!)).toBe(clicks(plain)); listen.mockRestore(); const link = screen.getByRole("link", { name: "Analytical Engine" }); expect(link).toHaveAttribute("href", "/projects/analytical-engine"); expect(screen.getAllByRole("link")).toHaveLength(1); expect(link).toHaveTextContent(/^Analytical Engine$/); expect(screen.getByRole("heading", { name: "Analytical Engine" })).toContainElement(link); const card = container.firstElementChild!; expect(card.tagName).toBe("ARTICLE"); expect(card).not.toHaveAttribute("role"); expect(card).not.toHaveAttribute("tabindex"); }); it("stretches a link from the heading slot, like a router's, as it does its own", () => { render(Card, { slots: { heading: () => h("a", { href: "/projects/analytical-engine" }, "Analytical Engine") }, }); const link = screen.getByRole("link", { name: "Analytical Engine" }); expect(screen.getAllByRole("link")).toHaveLength(1); expect(screen.getByRole("heading", { name: "Analytical Engine" })).toContainElement(link); }); it("reaches its link, then its actions, with Tab, and follows the link on Enter", async () => { const user = userEvent.setup(); // jsdom doesn't navigate, so this stands in for the browser following the link. const onNavigate = vi.fn((event: Event) => event.preventDefault()); document.addEventListener("click", onNavigate); render(Card, { props: { heading: "Analytical Engine", href: "/projects/analytical-engine" }, slots: { actions: () => [button("Share"), button("Save")] }, }); await user.tab(); expect(screen.getByRole("link", { name: "Analytical Engine" })).toHaveFocus(); await user.keyboard("{Enter}"); document.removeEventListener("click", onNavigate); expect(onNavigate).toHaveBeenCalledTimes(1); expect(onNavigate.mock.calls[0]![0].target).toBe(screen.getByRole("link")); await user.tab(); expect(screen.getByRole("button", { name: "Share" })).toHaveFocus(); await user.tab(); expect(screen.getByRole("button", { name: "Save" })).toHaveFocus(); }); it("keeps its actions out of the link, so pressing one runs it rather than following the link", async () => { const user = userEvent.setup(); const onSave = vi.fn(); render(Card, { props: { heading: "Analytical Engine", href: "/projects/analytical-engine" }, slots: { actions: () => button("Save", onSave) }, }); const save = screen.getByRole("button", { name: "Save" }); expect(screen.getByRole("link")).not.toContainElement(save); await user.click(save); expect(onSave).toHaveBeenCalledTimes(1); }); it("puts attributes, listeners and refs on its root", async () => { const user = userEvent.setup(); const onFocusin = vi.fn(); const card = ref<{ $el: HTMLElement }>(); render({ render: () => h( Card, { ref: card, id: "engine", class: "featured", "aria-labelledby": "engine-heading", href: "/projects/analytical-engine", onFocusin }, { heading: () => h("span", { id: "engine-heading" }, "Analytical Engine") }, ), }); const root = screen.getByRole("article", { name: "Analytical Engine" }); expect(root).toHaveAttribute("id", "engine"); expect(root).toHaveClass("card", "featured"); await user.tab(); expect(onFocusin).toHaveBeenCalled(); expect(card.value?.$el).toBe(root); }); it("renders the same markup every time, with its parts in a fixed order", () => { const options = { props: { heading: "Analytical Engine", href: "/projects/analytical-engine" }, slots: { eyebrow: () => "Project", media: image, default: () => "A mechanical computer.", actions: () => button("Save"), footer: () => "By Charles Babbage", }, }; const first = render(Card, options).container.innerHTML; const { container } = render(Card, options); expect(container.innerHTML).toBe(first); const parts = [...container.querySelectorAll("[data-slot]")].map((part) => part.getAttribute("data-slot")); expect(parts).toEqual(["header", "heading", "link", "eyebrow", "media", "body", "actions", "footer"]); expect(container.innerHTML).not.toMatch(/\bid=/); }); it("only renders the parts it's given", () => { const { container } = render(Card, { props: { heading: "Analytical Engine" } }); const parts = [...container.querySelectorAll("[data-slot]")].map((part) => part.getAttribute("data-slot")); expect(parts).toEqual(["header", "heading"]); }); }); ``` ::: :: ## Sources - [HTML Standard: the article element](https://html.spec.whatwg.org/multipage/sections.html#the-article-element){rel=""nofollow""}, [the section element](https://html.spec.whatwg.org/multipage/sections.html#the-section-element){rel=""nofollow""} and [the a element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element){rel=""nofollow""}, for what a card is, and why nothing interactive goes in a link - [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/){rel=""nofollow""} - [Understanding SC 1.4.11: Non-text Contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html){rel=""nofollow""}, for boundaries that text already identifies - [Understanding SC 2.4.4: Link Purpose (In Context)](https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html){rel=""nofollow""}, for links named by their heading - [Heydon Pickering, Inclusive Components: Cards](https://inclusive-components.design/cards/){rel=""nofollow""}, for the stretched link and the heading that comes first - [Adrian Roselli: Block Links, Cards, Clickable Regions, Rows, Etc.](https://adrianroselli.com/2020/02/block-links-cards-clickable-regions-etc.html){rel=""nofollow""}, for what goes wrong when the whole card is a link - [Bootstrap: Stretched link](https://getbootstrap.com/docs/5.3/helpers/stretched-link/){rel=""nofollow""}, for the pseudo-element that covers the card - [WebAIM: Screen Reader User Survey](https://webaim.org/projects/screenreadersurvey10/){rel=""nofollow""}, for how people find their way around a page by its headings - [Scott O'Hara: "Fixing" Lists](https://www.scottohara.me/blog/2019/01/12/lists-and-safari.html){rel=""nofollow""}, for lists that lose their role in Safari - [WAI-ARIA Authoring Practices: Feed](https://www.w3.org/WAI/ARIA/apg/patterns/feed/){rel=""nofollow""}, for lists of cards that load as people scroll # User Interface (UI) Let's start with how a checkbox group looks: its parts, its sizes, its orientation and how it shows each of its states. ## Anatomy ::checkbox-group-anatomy 1. **Group** — The `
          `, which holds the legend and every checkbox, and carries the size and orientation. 2. **Legend** — The ``, its first child, which names the group, usually with a question. 3. **Select all** — Optional. A Checkbox that checks or clears every option, and shows whether all, some or none are checked. 4. **Options** — A Checkbox for each option, which all share one `name`. 5. **Hint and error** — Optional. Paragraphs of their own, after the group, which its `
          ` points to by their `id`. :: Every group has a legend and its options. The select-all box is only there when you ask for one, and its options then sit in from it, so they read as its children. The hint and the error message sit outside the group, in the page, and its `
          ` points to them by their `id`. The parts always render in the same order, which you can see in the [DOM contract](https://opencomponents.dev/docs/components/checkbox-group/ax#deterministic). ## Sizes The `size` prop sets the size of every checkbox in the group, and of its legend, and `md` is the default. The names are the same as the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ui#sizes)'s, so a group reads at the same size as the inputs and buttons next to it. ::checkbox-group-sizes-example :::framework-switcher #react ```tsx Which emails would you like? {/* …sm, md, lg, xl */} ``` #vue ```vue Which emails would you like? ``` #svelte ```svelte Which emails would you like? ``` #angular ```angular-html
          Which emails would you like?
          ``` #solid ```tsx Which emails would you like? {/* …sm, md, lg, xl */} ``` #astro ```astro Which emails would you like? ``` #vanilla ```html
          Which emails would you like?
          ``` ::: :: | Size | Legend | Options' text | Indent under select all | | ---- | ------ | ------------- | ----------------------- | | `xs` | 12px | 12px | 20px | | `sm` | 14px | 14px | 24px | | `md` | 14px | 14px | 26px | | `lg` | 16px | 16px | 28px | | `xl` | 16px | 16px | 34px | Sizes are set in `rem`, and the table shows the values we recommend at the default text size of 16px. The legend is the same size as its options' text, in a heavier weight, so it reads as their heading without shouting over the rest of the form. The indent is the select-all box's width plus its gap, so each option's box lines up with the select-all box's label. Each checkbox keeps its 24 × 24px hit area at every size (see the Checkbox's [Sizes](https://opencomponents.dev/docs/components/checkbox/ui#sizes)). ## Orientation Options run in a column by default, one per line, and `orientation="horizontal"` puts them in a row, which wraps onto the next line when it runs out of room. ::checkbox-group-orientation-example :::framework-switcher #react ```tsx Which emails would you like? How can we reach you? ``` #vue ```vue Which emails would you like? How can we reach you? ``` #svelte ```svelte Which emails would you like? How can we reach you? ``` #angular ```angular-html
          Which emails would you like?
          How can we reach you?
          ``` #solid ```tsx Which emails would you like? How can we reach you? ``` #astro ```astro Which emails would you like? How can we reach you? ``` #vanilla ```html
          Which emails would you like?
          …
          How can we reach you?
          …
          ``` ::: :: We recommend the column for almost every group, which is why it's the default. Every label starts at the same edge, so people can scan down the list without hunting for where the next option begins, and every box sits right next to its own label, so nobody wonders whether a box belongs to the label on its left or on its right. A long label wraps under itself rather than pushing the next option onto another line, and the column still works on a narrow phone and at 200% zoom ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html){rel=""nofollow""}). Keep the row for two or three options with short labels, like "Email", "Phone" and "Post". ## States Each checkbox shows its own states, as on the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ui#states) page. On top of those, the group can be disabled or invalid as a whole, and a select-all box shows whether all, some or none of its options are checked. ::checkbox-group-states-example :::framework-switcher #react ```tsx Which emails would you like? Which emails would you like? Which emails would you like? Which emails would you like?

          Pick at least one email to sign up for

          ``` #vue ```vue Which emails would you like? Which emails would you like? Which emails would you like? Which emails would you like?

          Pick at least one email to sign up for

          ``` #svelte ```svelte Which emails would you like? Which emails would you like? Which emails would you like? Which emails would you like?

          Pick at least one email to sign up for

          ``` #angular ```angular-html
          Which emails would you like?
          Which emails would you like?
          Which emails would you like?
          Which emails would you like?

          Pick at least one email to sign up for

          ``` #solid ```tsx Which emails would you like? Which emails would you like? Which emails would you like? Which emails would you like?

          Pick at least one email to sign up for

          ``` #astro ```astro Which emails would you like? Which emails would you like? Which emails would you like? Which emails would you like?

          Pick at least one email to sign up for

          ``` #vanilla ```html
          Which emails would you like?
          Which emails would you like?
          …
          Which emails would you like?
          …
          Which emails would you like?

          Pick at least one email to sign up for

          ``` ::: :: | State | Selector | Recommended look | | ---------- | --------------------------------------------------- | --------------------------------------------------------------------- | | Disabled | `:disabled`, which a `
          ` matches | The legend at 50% opacity, and every checkbox looks disabled | | Invalid | `[aria-invalid="true"]`, which each option gets too | Each option's box with the Checkbox's invalid border | | Select all | Its ``'s `:checked` and `:indeterminate` | The Checkbox's check, or its dash while only some options are checked | The group draws no state of its own on the boxes. A disabled `
          ` disables every checkbox inside it, and each one looks disabled from `:disabled`, as it would on its own. An invalid group passes `aria-invalid` on to its options, so each box shows the Checkbox's invalid border, and the error message says what's wrong in words, since a red border alone can't ([WCAG 1.4.1](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html){rel=""nofollow""}). None of the states change the group's size or position. You'll find how each state behaves under [Every state](https://opencomponents.dev/docs/components/checkbox-group/ux#every-state). ## Tokens The group itself reads one [theme token](https://opencomponents.dev/docs/foundations/design-tokens#theme-tokens), and each of its checkboxes reads the Checkbox's [own five](https://opencomponents.dev/docs/components/checkbox/ui#tokens): | Token | Used for | | ----------------------- | ------------------------------------------------------------- | | `--color--neutral-text` | The legend, which needs 4.5:1 against the page, like any text | The legend is drawn in the same colour as the checkboxes' labels, so it has the same contrast as they do: 4.5:1 or more against the page with our reference tokens ([WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html){rel=""nofollow""}). You'll find the tokens themselves in the Button's [`tokens.css`](https://opencomponents.dev/docs/components/button#reference-implementation), which you can copy into your theme. If you need to tune a group, you can set its [own variables](https://opencomponents.dev/docs/foundations/design-tokens#component-variables), such as `--checkbox-group--row-gap` or `--checkbox-group--legend--font-size`, from a class. Each box sets the [Checkbox's variables](https://opencomponents.dev/docs/components/checkbox/ui#tokens) on itself, so a value on the group doesn't reach them. Set those from the same class with a descendant selector, like `.brand .checkbox`, written so that your framework's style scoping lets it through to the boxes, which the group renders: `:global()` in CSS Modules, Svelte and Astro, `:deep()` in Vue and `::ng-deep` in Angular, as below. The Checkbox Group's styles sit in the `components` cascade layer, so your class wins without any specificity tricks: ::framework-switcher #react ```tsx [Emails.tsx] import styles from "./Emails.module.css"; export function Emails() { return ( Which emails would you like? ); } ``` ```css [Emails.module.css] .brand { --checkbox-group--row-gap: 0.75rem; } /* The boxes' own class isn't this module's, so it stays global. */ .brand :global(.checkbox) { --checkbox--box--radius: 0; } ``` #vue ```vue ``` #svelte ```svelte Which emails would you like? ``` #angular ```angular-ts @Component({ selector: "app-emails", imports: [CheckboxGroup], template: `
          Which emails would you like?
          `, styles: ` .brand { --checkbox-group--row-gap: 0.75rem; } /* The boxes are in the CheckboxGroup's view, which this component's styles only reach with ::ng-deep. */ .brand ::ng-deep .checkbox { --checkbox--box--radius: 0; } `, }) export class Emails { emails = emails; } ``` #solid ```tsx [Emails.tsx] import styles from "./Emails.module.css"; export function Emails() { return ( Which emails would you like? ); } ``` ```css [Emails.module.css] .brand { --checkbox-group--row-gap: 0.75rem; } /* The boxes' own class isn't this module's, so it stays global. */ .brand :global(.checkbox) { --checkbox--box--radius: 0; } ``` #astro ```astro Which emails would you like? ``` #vanilla ```html
          Which emails would you like?
          …
          ``` :: ## UI Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------------------ | ------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------- | | `checkbox-group/legend-contrast` | Must | Component | The legend has a contrast of 4.5:1 against the page | WCAG 1.4.3 (AA) | axe `color-contrast`, contrast checker | | `checkbox-group/vertical-by-default` | Should | Component | Options run in a column unless it's set to a row, and a row wraps rather than overflowing | Open Components | Visual regression test | | `checkbox-group/option-spacing` | Should | Component | Options sit at least 8px apart in a column and 24px apart in a row | Open Components | Visual regression test | | `checkbox-group/select-all-indent` | Should | Component | Options under a select-all box sit in from it by its box and gap, so their boxes line up with its label | Open Components | Visual regression test | | `checkbox-group/resizable` | Must | Component | The legend, the gaps and the indent are sized in `rem`, and the legend and a row of options wrap instead of being clipped or scrolling sideways | Open Components, beyond WCAG 1.4.4, 1.4.10, 1.4.12 (AA) | 200% zoom | | `checkbox-group/disabled-look` | Must | Component | A disabled group shows its legend as disabled along with its boxes, in `GrayText` in forced colours mode | Open Components | Visual regression test, emulation | | `checkbox-group/stable-size` | Must | Component | No state changes the group's size or position | Open Components | Visual regression test | # User Experience (UX) Now let's look at how a checkbox group behaves for every person, input and setting. A good checkbox group is [accessible](https://opencomponents.dev/docs/components/checkbox-group/ux#accessible), [predictable](https://opencomponents.dev/docs/components/checkbox-group/ux#predictable), designed in [every state](https://opencomponents.dev/docs/components/checkbox-group/ux#every-state) and [adaptive](https://opencomponents.dev/docs/components/checkbox-group/ux#adaptive). ## Accessible ### Use a fieldset and a legend A `
          ` gives you the `group` role and `disabled` for every control inside it, and a `` as its first child gives the group its name, all for free. Screen readers announce the legend as people move into the group, so they hear "Which emails would you like?" before "Product news, checkbox, not checked", rather than a list of boxes with no question. A `
          ` with a paragraph above it only looks like a group, and a `
          ` still needs `aria-labelledby` to be named, and can't disable anything. ::framework-switcher #react ```tsx {/* Do: the legend names the group, and screen readers announce it with each box */}
          Which emails would you like?
          {/* Don't: the question is just a paragraph, so the boxes are announced without it */}

          Which emails would you like?

          ``` #vue ```vue
          Which emails would you like?

          Which emails would you like?

          ``` #svelte ```svelte
          Which emails would you like?

          Which emails would you like?

          ``` #angular ```angular-html
          Which emails would you like?

          Which emails would you like?

          ``` #solid ```tsx {/* Do: the legend names the group, and screen readers announce it with each box */}
          Which emails would you like?
          {/* Don't: the question is just a paragraph, so the boxes are announced without it */}

          Which emails would you like?

          ``` #astro ```astro
          Which emails would you like?

          Which emails would you like?

          ``` #vanilla ```html
          Which emails would you like?

          Which emails would you like?

          ``` :: The legend has to be the `
          `'s first child, which the [HTML Standard](https://html.spec.whatwg.org/multipage/form-elements.html#the-fieldset-element){rel=""nofollow""} asks for, and which is what names the group. The Checkbox Group renders its legend there for you, and resets the fieldset's border and padding, so it lines up with the rest of your form, without the browser's frame around it. ### Name and describe the group The legend says what the options are for, and it's best written as the question they answer, like "Which emails would you like?". It's the group's accessible name, so screen readers read it as people move into the group, voice control users can say it, and tests and agents use it to find the group. ::checkbox-group-hint-example :::framework-switcher #react ```tsx Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #vue ```vue Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #svelte ```svelte Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #angular ```angular-html
          Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #solid ```tsx Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #astro ```astro Which emails would you like?

          Pick as many as you like. You can stop them at any time.

          ``` #vanilla ```html
          Which emails would you like?
          …

          Pick as many as you like. You can stop them at any time.

          ``` ::: :: - Every group has a visible legend ([WCAG 1.3.1](https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html){rel=""nofollow""}, [3.3.2](https://www.w3.org/WAI/WCAG22/Understanding/labels-or-instructions.html){rel=""nofollow""}). Keep it short, since screen readers can repeat it for each box, and put anything longer in the hint. - A hint, like "Pick as many as you like", goes in the group's description. Keep it out of the legend, so it doesn't become part of the name, and point `aria-describedby` on the group at its `id`, which is what the [APG](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/){rel=""nofollow""} asks for a group's descriptive text. - An error message goes in the description too, after the hint, so the group's `aria-describedby` lists both IDs, the hint's first (see [Pick at least one](https://opencomponents.dev/docs/components/checkbox-group/ux#pick-at-least-one)). - Each option is a Checkbox, so its label follows the Checkbox's rules, from [`checkbox/visible-label`](https://opencomponents.dev/docs/components/checkbox/ux#ux-checklist) to [`checkbox/positive-label`](https://opencomponents.dev/docs/components/checkbox/ux#ux-checklist). The options take a value and a label and nothing else, so a hint about one option goes in the group's hint, naming the option it's about. ### Contrast and size - The legend needs a contrast of at least 4.5:1 with its background ([WCAG 1.4.3](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html){rel=""nofollow""}). A disabled group is exempt, but it should still be readable. - Each box, its focus ring and its hit area follow the Checkbox's [Contrast and size](https://opencomponents.dev/docs/components/checkbox/ux#contrast-and-size). - Stacked options sit 8px apart, so a tap that lands between two of them doesn't toggle the wrong one, and every option keeps its own 24 × 24px hit area ([WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html){rel=""nofollow""}). ## Predictable ### Keyboard | Key | Checkbox Group | | ------------------ | --------------------------------------------------------------------- | | `Tab`, `Shift+Tab` | Moves focus to the next or previous checkbox, select-all box included | | `Space` | Checks or unchecks the focused checkbox | | Arrow keys | Don't move focus between checkboxes | Every checkbox in a group is a stop of its own in the tab order, which is what the APG's [mixed-state example](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/examples/checkbox-mixed/){rel=""nofollow""} does, and what native checkboxes do. That's different from a Radio Group, where `Tab` reaches the group once and the arrow keys move between its options, because only one of them can be checked. In a checkbox group, people check each box on its own, so each one gets its own stop, and you don't need any roving focus to build one. ### Select all A select-all box lets people check or clear every option at once, which saves a lot of clicks in a long list. It's a Checkbox above the options that shows what they add up to: checked when every option is, unchecked when none is, and mixed, with a dash, when only some are. Screen readers announce it as "mixed", or "partially checked", so people know what it stands for before they press it. ::checkbox-group-select-all-example :::framework-switcher #react ```tsx const [picked, setPicked] = useState(["news"]); Which emails would you like?

          You'll get {picked.length} of {emails.length}

          ``` #vue ```vue ``` #svelte ```svelte Which emails would you like?

          You'll get {picked.length} of {emails.length}

          ``` #angular ```angular-html
          Which emails would you like?

          You'll get {{ picked().length }} of {{ emails.length }}

          ``` #solid ```tsx const [picked, setPicked] = createSignal(["news"]); Which emails would you like?

          You'll get {picked().length} of {emails.length}

          ``` #astro ```astro Which emails would you like? ``` #vanilla ```html
          Which emails would you like?
          ``` ::: :: - Checking it, from unchecked or from mixed, checks every option, and unchecking it clears them all, which is what the [APG](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/){rel=""nofollow""} asks for. Try it above: check one option, and the box turns mixed, then press it, and every option is checked. - It doesn't go back to the options people had picked before, the way the APG's own example does as a third step. The APG leaves that up to you, and we leave it out, since a box that does something different on every third press is hard to predict, and it's never clear which earlier selection it'll bring back. - Its state is worked out from the options every time they change, never kept on its own, so it can't disagree with them, as [`checkbox/derived-mixed`](https://opencomponents.dev/docs/components/checkbox/ux#ux-checklist) asks. - It has no `name`, so its form never sends it. It stands for the options, and they're what the form sends. - Label it with what it selects, like "All emails", rather than "Select all" on its own, so it still makes sense out of context. It's best kept for longer lists, or for lists that people often want all of, since in a group of two or three it's one more box to read. ### Keep options in a column People read a checkbox group from top to bottom, one option per line, and that's how the Checkbox Group lays them out unless you ask for a row (see [Orientation](https://opencomponents.dev/docs/components/checkbox-group/ui#orientation)). A column keeps each box next to its own label, lets long labels wrap under themselves, and still fits on a phone, which a row of more than a few options doesn't. Order the options in a way people can predict, like from most to least common, or alphabetically for a long list, and keep the same order every time the group shows up, so people who've used it before find each option where they left it. ## Every state ### Disabled `disabled` on the Checkbox Group sets `disabled` on its `
          `, which disables every checkbox inside it, select-all box included. None of them can be focused, toggled or sent with the form, and each one looks disabled on its own, since the Checkbox's look comes from `:disabled`, which matches inside a `
          ` too (see [`checkbox/disabled-inert`](https://opencomponents.dev/docs/components/checkbox/ux#ux-checklist)). The legend fades with them, so the whole group reads as one that's out of use. As with a single checkbox, we recommend disabling as little as you can, since keyboard users can't reach a disabled group to find out why it's disabled ([`checkbox/explain-disabled`](https://opencomponents.dev/docs/components/checkbox/ux#ux-checklist)). Explain why next to it, or leave the group out until it applies. ### Pick at least one Most checkbox groups are optional, since checking nothing is an answer too. Sometimes people have to pick at least one, though, like choosing which emails to sign up for on a page that's only there to sign up. That's a rule about the group, and HTML has no way to say it. `required` on a checkbox means that box has to be checked, so putting it on every box asks people to check them all, and putting it on one box asks for that one in particular. So say it in the hint, check it in your own code when people submit, and report it on the group. ::checkbox-group-validation-example :::framework-switcher #react ```tsx import { useRef, useState, type FormEvent } from "react"; import { flushSync } from "react-dom"; export function SignUp() { const [picked, setPicked] = useState([]); const [error, setError] = useState(""); const [status, setStatus] = useState(""); const group = useRef(null); function update(value: string[]) { setPicked(value); // Picking one fixes the error, so it clears right away. if (value.length) setError(""); } async function signUp(event: FormEvent) { event.preventDefault(); if (!picked.length) { // Focus the first box once the error is in the page, so screen readers read it with the group. flushSync(() => { setError("Pick at least one email to sign up for"); setStatus("Couldn't sign you up. Pick at least one email."); }); group.current?.querySelector("input")?.focus(); return; } await api.signUp(picked); setStatus("You're signed up"); } return (
          Which emails would you like?

          Pick at least one.

          {error &&

          {error}

          }

          {status}

          ); } ``` #vue ```vue ``` #svelte ```svelte
          Which emails would you like?

          Pick at least one.

          {#if error}

          {error}

          {/if}

          {status}

          ``` #angular ```angular-ts import { Component, ElementRef, Injector, afterNextRender, inject, signal, viewChild } from "@angular/core"; @Component({ selector: "app-sign-up", imports: [CheckboxGroup, Button], template: `
          Which emails would you like?

          Pick at least one.

          @if (error()) {

          {{ error() }}

          }

          {{ status() }}

          `, }) export class SignUp { emails = emails; picked = signal([]); error = signal(""); status = signal(""); // On a component's element, a template variable is the component, so read its element instead. group = viewChild.required("group", { read: ElementRef }); injector = inject(Injector); update(value: string[]) { this.picked.set(value); // Picking one fixes the error, so it clears right away. if (value.length) this.error.set(""); } async signUp(event: SubmitEvent) { event.preventDefault(); if (!this.picked().length) { this.error.set("Pick at least one email to sign up for"); this.status.set("Couldn't sign you up. Pick at least one email."); // Focus the first box once the error is in the page, so screen readers read it with the group. afterNextRender(() => this.group().nativeElement.querySelector("input")?.focus(), { injector: this.injector }); return; } await api.signUp(this.picked()); this.status.set("You're signed up"); } } ``` #solid ```tsx import { Show, createSignal } from "solid-js"; export function SignUp() { const [picked, setPicked] = createSignal([]); const [error, setError] = createSignal(""); const [status, setStatus] = createSignal(""); let group!: HTMLFieldSetElement; function update(value: string[]) { setPicked(value); // Picking one fixes the error, so it clears right away. if (value.length) setError(""); } async function signUp(event: SubmitEvent) { event.preventDefault(); if (!picked().length) { setError("Pick at least one email to sign up for"); setStatus("Couldn't sign you up. Pick at least one email."); // Solid updates the page as soon as a signal changes, so the error is already in it. group.querySelector("input")?.focus(); return; } await api.signUp(picked()); setStatus("You're signed up"); } return (
          Which emails would you like?

          Pick at least one.

          {error()}

          {status()}

          ); } ``` #astro ```astro
          Which emails would you like?

          Pick at least one.

          ``` #vanilla ```html
          Which emails would you like?

          Pick at least one.

          ``` ::: :: - Say that people need to pick one before they try, in the hint or in the legend, like "Pick at least one" ([WCAG 3.3.2](https://www.w3.org/WAI/WCAG22/Understanding/labels-or-instructions.html){rel=""nofollow""}). There's no `required` to announce it for you. - Check it when people submit, rather than as they move through the boxes, since every box is unchecked until they've picked one. Once the error shows, clear it as soon as they check a box. - Set `aria-invalid="true"` on the group while its error message shows, and add the message to the group's `aria-describedby`, after the hint ([WCAG 3.3.1](https://www.w3.org/WAI/WCAG22/Understanding/error-identification.html){rel=""nofollow""}). The Checkbox Group passes `aria-invalid` on to each option, so every box shows the invalid border and is announced as invalid as people reach it, since not every screen reader reads a group's description when focus moves into it. - Say what to pick, as in "Pick at least one email to sign up for", rather than "This field is required" ([WCAG 3.3.3](https://www.w3.org/WAI/WCAG22/Understanding/error-suggestion.html){rel=""nofollow""}). - When a submit fails, move focus to the group's first checkbox, once the error is in the page, as on the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ux#required-and-invalid). The status message says what happened even when the focus doesn't move. - Put `novalidate` on the form, as on the Checkbox and the Input, so the browser's own error bubbles don't compete with yours. The same goes for a group with a limit, like at most three options: check it in your code and report it on the group. ## Adaptive ### Pointer, touch and pen - Each option toggles from anywhere in its box's hit area or on its label, as described in the Checkbox's [Pointer, touch and pen](https://opencomponents.dev/docs/components/checkbox/ux#pointer-touch-and-pen). A press on the legend does nothing, since it names the group rather than one of its boxes. - Stacked options sit 8px apart, and options in a row 24px apart, so a tap that lands between two doesn't toggle the wrong one. ### More contrast When someone asks for more contrast (`prefers-contrast: more`), each box's border is drawn at full strength, as on the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ux#more-contrast). The legend already passes, so it stays as it is. ### Forced colours Windows contrast themes replace every colour with the user's own. Each box keeps its own forced-colours look, as on the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ux#forced-colours), and a disabled group's legend is drawn in `GrayText`, the system's colour for disabled text, like its boxes. ### Colour scheme The tokens use `light-dark()`, which follows `color-scheme`, so the Checkbox Group adapts to your light and dark themes on its own. ### Text size and spacing The legend, the gaps and the indent are set in `rem`, so the whole group grows with its text at 200% text size ([WCAG 1.4.4](https://www.w3.org/WAI/WCAG22/Understanding/resize-text.html){rel=""nofollow""}) and with wider line, letter and word spacing ([WCAG 1.4.12](https://www.w3.org/WAI/WCAG22/Understanding/text-spacing.html){rel=""nofollow""}). A long legend wraps rather than being clipped, and a row of options wraps onto the next line rather than scrolling sideways at 320px wide ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html){rel=""nofollow""}). ### Languages and direction The Checkbox Group indents its options with `padding-inline-start`, and each Checkbox lays out its box and label in a grid that follows the reading direction, so the whole group mirrors in right-to-left languages, with no extra work on your part: ::checkbox-group-languages-example :::framework-switcher #react ```tsx
          ما الرسائل التي تريدها؟
          ``` #vue ```vue
          ما الرسائل التي تريدها؟
          ``` #svelte ```svelte
          ما الرسائل التي تريدها؟
          ``` #angular ```angular-html
          ما الرسائل التي تريدها؟
          ``` #solid ```tsx
          ما الرسائل التي تريدها؟
          ``` #astro ```astro
          ما الرسائل التي تريدها؟
          ``` #vanilla ```html
          ما الرسائل التي تريدها؟
          …
          ``` ::: :: - The options sit in from the select-all box on the right in a right-to-left layout, since the indent is on the start side. - Remember to translate the legend, the options, the hint and the error message along with the rest of the page, and to mark any that are in another language with `lang`, so that screen readers pronounce them correctly ([WCAG 3.1.2](https://www.w3.org/WAI/WCAG22/Understanding/language-of-parts.html){rel=""nofollow""}). ## UX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ---------------------------------- | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------ | | `checkbox-group/fieldset` | Must | Component | It's a `
          ` whose first child is the `` that names it, so it has the `group` role and the legend as its name | WCAG 1.3.1, 4.1.2 (A), HTML | Unit test | | `checkbox-group/legend-question` | Must | Usage | Every group has a visible legend that says what its options are for, ideally as the question they answer | WCAG 1.3.1, 3.3.2 (A) | Review | | `checkbox-group/described` | Should | Both | A hint and an error message sit outside the legend and are linked to the `
          ` with `aria-describedby`, the hint's ID first | WCAG 1.3.1 (A), APG | Unit test, screen reader | | `checkbox-group/keyboard` | Must | Component | `Tab` reaches each box in turn, select-all box included, `Space` toggles the focused one, and the arrow keys never move focus between them | WCAG 2.1.1 (A), APG | Unit test | | `checkbox-group/select-all-state` | Must | Component | The select-all box is checked when every option is, unchecked when none is, and mixed when only some are, worked out from them whenever they change | WCAG 4.1.2 (A), APG | Unit test | | `checkbox-group/select-all-action` | Must | Component | Checking the select-all box, from unchecked or mixed, checks every option, and unchecking it clears them all, without going back to an earlier selection | APG, Open Components | Unit test | | `checkbox-group/select-all-label` | Should | Usage | A select-all box says what it selects, like "All emails", and only comes with lists that are long or often picked in full | Open Components | Review | | `checkbox-group/vertical` | Should | Usage | Options run in a column, and only two or three short ones run in a row | Open Components | Review | | `checkbox-group/predictable-order` | Should | Usage | Options come in an order people can predict, like most to least common or alphabetical, and keep it every time | Open Components | Review | | `checkbox-group/at-least-one` | Must | Usage | A group people have to pick from says so in its legend or hint, and is checked in code when the form is sent, never with `required` on its boxes | HTML, WCAG 3.3.2 (A) | Review | | `checkbox-group/error-message` | Must | Usage | An invalid group has an error message, in text and linked to the `
          ` with `aria-describedby`, that says what to pick | WCAG 1.4.1, 3.3.1 (A), 3.3.3 (AA) | Screen reader | | `checkbox-group/invalid-state` | Must | Both | The group sets `aria-invalid="true"` while its error message shows, and each of its options looks and reads invalid with it | WCAG 4.1.2 (A), Open Components | Unit test | | `checkbox-group/focus-on-error` | Should | Usage | A failed submit moves focus to the group's first box, once the error is in the page | Open Components, beyond WCAG 3.3.1 (A) | Keyboard | | `checkbox-group/disabled-inert` | Must | Component | A disabled group sets `disabled` on its `
          `, so no box in it, select-all box included, can be focused, toggled or sent | HTML | Unit test | | `checkbox-group/mirrors-in-rtl` | Should | Component | The indent and a row of options follow `dir`, with logical properties | Open Components | Review | ## FAQ ### Checkbox Group or something else? A Checkbox Group lets people pick any number of options from a short list. For anything else, another component will do a better job: | When people need to… | Use | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | | Pick any number of options out of a few | Checkbox Group | | Say yes or no to one thing, like agreeing to the terms | [Checkbox](https://opencomponents.dev/docs/components/checkbox) | | Pick one option out of a few | Radio Group | | Pick one option, or several, out of many | [Select](https://opencomponents.dev/docs/components/select), or [Combobox](https://opencomponents.dev/docs/components/combobox) | | Flip settings that take effect right away, like alerts | A [Switch](https://opencomponents.dev/docs/components/switch) for each | | Select rows in a table | A Checkbox in each row, with an `aria-label` | The [Combobox](https://opencomponents.dev/docs/components/combobox) picks several values too, when the list is long enough that people would rather type than scroll. ::accordion :::accordion-item{label="Why can't I make a group required?"} Because HTML has no way to say it. `required` on a checkbox means that one box has to be checked, so a form with `required` on every box asks for all of them, and the browser's message names one box rather than the group. A radio group is different, since one `required` radio makes the whole group required. So for a checkbox group, say "Pick at least one" in the hint, check the value when people submit, and show the error on the group, as under [Pick at least one](https://opencomponents.dev/docs/components/checkbox-group/ux#pick-at-least-one) . ::: :::accordion-item --- label: Why doesn't the Checkbox Group use roving focus, like a radio group? --- Because people check each box on its own. In a radio group, checking one option unchecks the others, so the group is one choice and one tab stop, and the arrow keys move the choice. In a checkbox group, each box is a choice of its own, so each one is a tab stop, and `Space` toggles the one that has focus, which is how native checkboxes have always worked. ::: :::accordion-item --- label: Why doesn't the select-all box bring back my last selection? --- Because a box should do what it shows. The APG allows a select-all box that cycles from mixed to all, to none and back to the options people had picked, but then the same press does something different each time, and nothing on screen says which. Ours checks every option from unchecked or mixed, and clears them all from checked, which is what the APG asks every select-all box to do. ::: :: # Developer Experience (DX) Next, let's look at how developers use the Checkbox Group. It has one API, with the same names as the Checkbox and every other component, it's typed end to end, and it works with your forms however you build them. ::framework-switcher #react ```tsx import { useState } from "react"; import { CheckboxGroup } from "@/components/CheckboxGroup"; const emails = [ { value: "news", label: "Product news" }, { value: "tips", label: "Tips and guides" }, { value: "events", label: "Events near you" }, ]; export function Emails() { const [picked, setPicked] = useState([]); return ( Which emails would you like? ); } ``` #vue ```vue ``` #svelte ```svelte Which emails would you like? ``` #angular ```angular-ts import { Component, signal } from "@angular/core"; import { CheckboxGroup } from "./checkbox-group"; @Component({ selector: "app-emails", imports: [CheckboxGroup], template: `
          Which emails would you like?
          `, }) export class Emails { emails = [ { value: "news", label: "Product news" }, { value: "tips", label: "Tips and guides" }, { value: "events", label: "Events near you" }, ]; picked = signal([]); } ``` #solid ```tsx import { createSignal } from "solid-js"; import { CheckboxGroup } from "~/components/CheckboxGroup"; const emails = [ { value: "news", label: "Product news" }, { value: "tips", label: "Tips and guides" }, { value: "events", label: "Events near you" }, ]; export function Emails() { const [picked, setPicked] = createSignal([]); return ( Which emails would you like? ); } ``` #astro ```astro --- import CheckboxGroup from "../components/CheckboxGroup.astro"; const emails = [ { value: "news", label: "Product news" }, { value: "tips", label: "Tips and guides" }, { value: "events", label: "Events near you" }, ]; --- Which emails would you like? ``` #vanilla ```html
          Which emails would you like?
          ``` :: ## Consistent Once you've learned the [Checkbox](https://opencomponents.dev/docs/components/checkbox/dx#consistent)'s API, you already know most of the Checkbox Group's. These names mean the same thing everywhere in Open Components: | Name | Kind | What it means | | ------------- | ---- | ----------------------------------------------------------------------------------------- | | `size` | Prop | `xs`, `sm`, `md`, `lg` or `xl`, with the same text everywhere | | `disabled` | Prop | The component can't be used, and here, nothing inside it either | | `name` | Prop | The name its form sends it under, which every one of its boxes shares | | `value` | Prop | The checked options' values, which you bind the way your framework binds a form control's | | `options` | Prop | What people can pick from, each with a `value` and a `label` | | `orientation` | Prop | `vertical` or `horizontal`, the way its options run | | `selectAll` | Prop | The label of a box that checks or clears every option | | Default slot | Slot | The legend, which names it, as the label names a Checkbox | We recommend `size="md"` and `orientation="vertical"` as the defaults. The Checkbox Group also leaves a few things out, on purpose: - There are no Checkboxes between its tags. The options are a prop, so the group can render a Checkbox for each one, give them all its `name`, bind each one to its value and work out the select-all box for you, and a list of options from your data drops straight in. - There's no `required`. HTML has no way to require one of a group of checkboxes, so the group leaves it to your code, as under [Pick at least one](https://opencomponents.dev/docs/components/checkbox-group/ux#pick-at-least-one). - There's no `hint` or `error`. Each of them is an element of its own, linked by ID, as on the Checkbox and the Input, so the group fits any layout. - There's no `color` or `variant`, since its boxes have none either. ## Type-safe Props, events and slots are typed, so your editor can autocomplete them and your type checker (`tsc`, `vue-tsc`, `svelte-check`, `ngc` or `astro check`) catches mistakes like `orientation="row"`, which isn't one of the orientations, or a value that isn't a list. | Prop | Type | Default | Description | | ------------- | ---------------------------------- | ------------ | ---------------------------------------------------------------------------------- | | `options` | `CheckboxGroupOption[]` | | One Checkbox for each, in this order | | `name` | `string` | | The name every box shares, which its form sends | | `value` | `string[]` | `[]` | The checked options' values, when you bind it. Without it, the group keeps its own | | `size` | `"xs" | "sm" | "md" | "lg" | "xl"` | `"md"` | How big its boxes, their labels and its legend are | | `orientation` | `"vertical" | "horizontal"` | `"vertical"` | Whether its options run in a column or in a row | | `disabled` | `boolean` | `false` | Disables every box in it, with `
          ` | | `selectAll` | `string` | | The label of a select-all box above the options. Without it, there's none | | Option field | Type | Description | | ------------ | -------- | ---------------------------------------------------------------- | | `value` | `string` | What the form sends while it's checked, and what the value lists | | `label` | `string` | The text that names its Checkbox | | Event | Payload | Description | | -------- | ------- | ---------------------------------------------------------------------------- | | `change` | `Event` | Fires when people check or uncheck any of its boxes, select-all box included | It comes from the box that changed, and bubbles up to the `
          `, so one listener hears every box, and `event.target` is the one that changed. A binding to `value` follows the group for you, with the new list of values. | Slot | Description | | ------- | --------------------------------- | | Default | The legend, which names the group | We also export `CheckboxGroupProps` and `CheckboxGroupOption`, which come in handy for wrappers and options from your data: ::framework-switcher #react ```ts import type { CheckboxGroupOption } from "@/components/CheckboxGroup"; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` #vue ```ts import type { CheckboxGroupOption } from "@/components/CheckboxGroup.vue"; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` #svelte ```ts import type { CheckboxGroupOption } from "$lib/components/CheckboxGroup.svelte"; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` #angular ```ts import type { CheckboxGroupOption } from "./checkbox-group"; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` #solid ```ts import type { CheckboxGroupOption } from "~/components/CheckboxGroup"; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` #astro ```ts import type { ComponentProps } from "astro/types"; import CheckboxGroup from "../components/CheckboxGroup.astro"; type CheckboxGroupOption = ComponentProps["options"][number]; const emails: CheckboxGroupOption[] = topics.map((topic) => ({ value: topic.id, label: topic.title })); ``` :: ## Composable The Checkbox Group renders a `
          `, and everything you pass it that isn't a prop lands there, including `id`, `class`, ARIA attributes and event listeners. A ref to the Checkbox Group reaches the `
          ` too, which is what you need to focus its first box when a submit fails. ### Forms Every box shares the group's `name`, and each checked box sends it with its own `value`, so the form sends one field with a value for each checked option, in the options' order, and nothing at all while none is checked. Read it with `getAll()`, since `get()` only returns the first value. That also means the form works before your JavaScript loads. ::framework-switcher #react ```tsx import type { FormEvent } from "react"; export function Preferences() { function save(event: FormEvent) { event.preventDefault(); const data = new FormData(event.currentTarget); // One name, with a value for each checked option, so read them all. api.savePreferences({ emails: data.getAll("emails") }); } return (
          Which emails would you like?
          ); } ``` #vue ```vue ``` #svelte ```svelte
          Which emails would you like?
          ``` #angular ```angular-ts @Component({ selector: "app-preferences", imports: [CheckboxGroup, Button], template: `
          Which emails would you like?
          `, }) export class Preferences { emails = emails; save(event: SubmitEvent) { event.preventDefault(); const data = new FormData(event.target as HTMLFormElement); // One name, with a value for each checked option, so read them all. api.savePreferences({ emails: data.getAll("emails") }); } } ``` #solid ```tsx export function Preferences() { function save(event: SubmitEvent & { currentTarget: HTMLFormElement }) { event.preventDefault(); const data = new FormData(event.currentTarget); // One name, with a value for each checked option, so read them all. api.savePreferences({ emails: data.getAll("emails") }); } return (
          Which emails would you like?
          ); } ``` #astro ```astro
          Which emails would you like?
          ``` #vanilla ```html
          Which emails would you like?
          ``` :: Keep in mind that a server reading the form sees `emails=news&emails=tips`, the same name once for each checked option, and no field at all when none is checked. Some frameworks keep only the last value of a repeated name unless you ask for all of them, like PHP, which needs the name to end in `[]`, so check how yours reads it. ### With other components - Each option is a [Checkbox](https://opencomponents.dev/docs/components/checkbox), which sets its own variables on itself. To restyle every box in a group, set them from a class on the group with a descendant selector, like `.brand .checkbox { --checkbox--box--fill: … }`, that gets past your framework's style scoping, as under [Tokens](https://opencomponents.dev/docs/components/checkbox-group/ui#tokens). A value on the group itself doesn't reach them. - The [Field](https://opencomponents.dev/docs/components/field) renders a group's hint and error message, and sets its `aria-describedby` and `aria-invalid`, as it does for the Checkbox and the [Input](https://opencomponents.dev/docs/components/input). - A [Button](https://opencomponents.dev/docs/components/button) that submits the form goes after the group, and takes the same `size`, so their text lines up. ## Controllable The Checkbox Group doesn't keep any state you can't reach. Its value is yours to bind, or to leave to the group, and every other state is a prop or an attribute that you control: ::checkbox-group-controlled-example :::framework-switcher #react ```tsx const [picked, setPicked] = useState(["news"]); Which emails would you like?

          You picked: {picked.join(", ") || "nothing yet"}

          How can we reach you? ``` #vue ```vue ``` #svelte ```svelte Which emails would you like?

          You picked: {picked.join(", ") || "nothing yet"}

          How can we reach you? ``` #angular ```angular-html
          Which emails would you like?

          You picked: {{ picked().join(", ") || "nothing yet" }}

          How can we reach you?
          ``` #solid ```tsx const [picked, setPicked] = createSignal(["news"]); Which emails would you like?

          You picked: {picked().join(", ") || "nothing yet"}

          How can we reach you? ``` #astro ```astro Which emails would you like?

          You picked: news

          How can we reach you? ``` #vanilla ```html
          Which emails would you like?
          …

          You picked: news

          How can we reach you?
          …
          ``` ::: :: | State | How you control it | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Value | `value`, bound to your state, or left to the group | | Select all | `selectAll`, with its checked and mixed states worked out from the value | | Disabled | `disabled`, or a `
          ` around it | | Invalid | `aria-invalid`, set while its error message shows (see [Pick at least one](https://opencomponents.dev/docs/components/checkbox-group/ux#pick-at-least-one)) | | Focus | A ref to its `
          `, and `focus()` on its first box | When you bind `value`, the boxes always show the list you hold. If a change doesn't make it into your state, like an option people aren't allowed to drop, the box goes back as soon as it renders, and so does the select-all box. When you don't bind it, the group keeps its own value, and starts out from the one you give it. ## DX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------------------ | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------- | | `checkbox-group/shared-vocabulary` | Must | Component | It uses the shared names: `size`, `disabled`, `name`, `value`, `options`, `orientation`, `selectAll`, the default slot for its legend and `change` | Open Components | Review | | `checkbox-group/typed` | Must | Component | Props, events and slots are typed, with unions rather than `string`, and the value is a list of strings | Open Components | Type check | | `checkbox-group/composes-checkbox` | Must | Component | Each option and the select-all box is a Checkbox, so every Checkbox rule holds for each of them | Open Components | Review | | `checkbox-group/form-control` | Must | Component | Every option shares one `name`, and its form sends a value for each checked option, in the options' order, and nothing for the select-all box | HTML | Unit test | | `checkbox-group/controllable` | Should | Component | `value` is a list that can be bound or left to the group, and a bound group always shows the value you hold | Open Components | Unit test | | `checkbox-group/fieldset-attributes` | Must | Component | Attributes, listeners and refs land on the `
          `, and each box's `change` bubbles up to it | Open Components | Unit test | ## FAQ ::accordion :::accordion-item --- label: Why are the options a prop, rather than Checkboxes inside it? --- So the group can do the work that's easy to get wrong. It gives every box the same `name` , binds each one to the value, keeps them in order and works out the select-all box from them, none of which you'd want to repeat on every box. A list of options also comes straight from your data, like a list of topics from your server. ::: :::accordion-item{label="Does the Checkbox Group work before JavaScript loads?"} Yes, as far as HTML can take it. The server renders a real `
          ` , its legend and a real checkbox for each option, so even before the page hydrates, people can check them and the form sends them. Only the select-all box has to wait: its mixed state is a property that only JavaScript can set, and checking every option from it takes a script, so until then it's a box that does nothing on its own. ::: :: # Agentic Experience (AX) Finally, let's look at how agents read, check and verify a checkbox group. They rely on the same accessibility tree as assistive technologies, and on a contract they can check the code against. ## Semantic Agents that drive a browser, through Playwright or a browser MCP server, read the page through its accessibility tree, which is made of roles, names and states. This is how they see the select-all example on this page: ```yaml - group "Which emails would you like?": - checkbox "All emails" [checked=mixed] - checkbox "Product news" [checked] - checkbox "Tips and guides" - checkbox "Events near you" ``` A heading or a paragraph above some boxes is only text, so an agent can't tell which boxes belong to which question, any more than a screen reader user can. With a named group, an agent can find the question, pick from it and confirm what it picked: ```ts const emails = page.getByRole("group", { name: "Which emails would you like?" }); await emails.getByRole("checkbox", { name: "All emails" }).check(); for (const box of await emails.getByRole("checkbox").all()) await expect(box).toBeChecked(); ``` ## Described Here's the whole contract in one block, for agents to read before they build or review a checkbox group: ```yaml component: CheckboxGroup summary: Lets people pick any number of options from a short list. Its legend names it, and each option is a Checkbox. standard: https://opencomponents.dev/docs/components/checkbox-group element: fieldset # its first child is the legend that names it. It takes every attribute that isn't a prop role: group props: options: { type: "{ value: string, label: string }[]" } # a Checkbox for each, in this order name: { type: string } # shared by every box, so the form sends one field with a value per checked option value: { type: "string[]", default: [] } # the checked options' values, in their order, when it's bound. Without it, the group keeps its own size: { type: [xs, sm, md, lg, xl], default: md } orientation: { type: [vertical, horizontal], default: vertical } disabled: { type: boolean, default: false } # sets disabled on the fieldset selectAll: { type: string } # the label of a box above the options that checks or clears them all slots: default: The legend, which names the group. events: change: Event, from the box that changed, which bubbles up to the fieldset. states: disabled: ":disabled, from
          , which every box inside it matches too" invalid: "[aria-invalid=true], which each option gets too, never :invalid" select-all: "> [data-slot=select-all] input:checked when every option is, :indeterminate when only some are" keyboard: Tab: Moves focus to the next box, select-all box included. There's no roving focus. Space: Checks or unchecks the focused box. On the select-all box, it checks every option, or clears them all. parts: [legend, select-all, options] # data-slot, in this order. Only select-all is optional tokens: theme: ["--color--neutral-text"] # and the Checkbox's, through its boxes variables: [--checkbox-group--legend--font-size, --checkbox-group--legend--margin-bottom, --checkbox-group--indent, --checkbox-group--row-gap, --checkbox-group--column-gap] layer: components # in Tailwind's order: theme, base, components, utilities rules: https://opencomponents.dev/docs/components/checkbox-group#checklist ``` It's also published on its own at [`/raw/docs/components/checkbox-group.yaml`](https://opencomponents.dev/raw/docs/components/checkbox-group.yaml){external=""}, with every rule from the checklist in place of the `rules` link. Its boxes follow the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ax#described)'s contract too, so give agents both. Every rule has a stable ID, like `checkbox-group/select-all-state`, so you and your agents can cite it in reviews and commits. ## Deterministic The same props always render the same markup, leaving out anything your framework adds for itself, like comments or scoping attributes. For example, here's a group with a select-all box and two options, "Product news" (`news`) and "Tips and guides" (`tips`), described by its hint: ```html Which emails would you like? ``` And here's what it renders: ```html
          Which emails would you like?
          ``` - The size and the orientation are mirrored as `data-size` and `data-orientation`, which are always there, and every box takes the group's `data-size`. - Parts are marked with `data-slot` and always come in the same order: `legend`, `select-all` and `options`. Only the select-all box is optional, and each box inside follows the [Checkbox](https://opencomponents.dev/docs/components/checkbox/ax#deterministic)'s DOM contract. - States change properties and attributes, never elements. The select-all box's mixed state is a property of its ``, so it never shows up in the markup, and no box is ever replaced as people check and uncheck them, so focus and the screen reader's position survive every change. - There's nothing random or generated, like IDs or timestamps, so the markup is the same on the server, on the client and in every snapshot. The legend names the `
          ` without an ID. The select-all box has no `aria-controls`, which the APG's example gives it. We leave it out on purpose, since it would need an ID on every option, and the `
          ` already ties the box to the options inside it. ## Verifiable Every rule in the checklist can be checked, and about two thirds of them automatically. ### Unit tests Every rule that the checklist checks with a unit test has one in `CheckboxGroup.test.ts`, which you'll find under [Reference implementation](https://opencomponents.dev/docs/components/checkbox-group#reference-implementation). We run them on every change to this page, so the code you see always passes them. ### In the browser In the browser, you can run [axe](https://github.com/dequelabs/axe-core){rel=""nofollow""} to check labels and contrast, and use the keyboard and the select-all box the way an agent would: ```ts import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; test("the emails group is named, reached one box at a time, and its select-all box checks them all", async ({ page }) => { await page.goto("/preferences"); const emails = page.getByRole("group", { name: "Which emails would you like?" }); const all = emails.getByRole("checkbox", { name: "All emails" }); await all.focus(); await page.keyboard.press("Tab"); await expect(emails.getByRole("checkbox", { name: "Product news" })).toBeFocused(); await page.keyboard.press("Space"); await expect(all).toBeChecked({ indeterminate: true }); await all.check(); for (const box of await emails.getByRole("checkbox").all()) await expect(box).toBeChecked(); const { violations } = await new AxeBuilder({ page }) .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]) .analyze(); expect(violations).toEqual([]); }); ``` Some things still need a human, so try your groups with the keyboard alone, with a screen reader, which should announce the legend as you move into the group and the select-all box as mixed, and at 200% zoom, with forced colours and more contrast turned on. You can emulate the last two in Chrome DevTools, under Rendering. ### During development Our reference implementation also warns you in the console as soon as a group renders without a legend, which leaves screen reader users with a list of boxes and no question. ### Prompts You can point your agent straight at this page. To build a checkbox group, you could use: ::framework-switcher #react ```text Build a Checkbox Group component for our React design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vue ```text Build a Checkbox Group component for our Vue 3 design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #svelte ```text Build a Checkbox Group component for our Svelte 5 design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #angular ```text Build a Checkbox Group component for our Angular design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #solid ```text Build a Checkbox Group component for our Solid design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #astro ```text Build a Checkbox Group component for our Astro design system that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vanilla ```text Build a Checkbox Group for our design system in plain HTML, CSS and JavaScript that meets the Open Components Checkbox Group standard: https://opencomponents.dev/raw/docs/components/checkbox-group.md Follow its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` :: To review one, the contract is enough: ```text Review our Checkbox Group against the Open Components Checkbox Group contract: https://opencomponents.dev/raw/docs/components/checkbox-group.yaml For each rule with a component or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` And to review how a screen uses its checkbox groups: ```text Review how our preferences page uses its checkbox groups against the Open Components Checkbox Group contract: https://opencomponents.dev/raw/docs/components/checkbox-group.yaml For each rule with a usage or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` ## AX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ---------------------------------- | ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | --------------- | --------- | | `checkbox-group/role-and-name` | Must | Component | It can be found by its legend alone, with `getByRole("group", { name })`, and each option inside it with `getByRole("checkbox", { name })` | WCAG 4.1.2 (A) | Unit test | | `checkbox-group/deterministic-dom` | Must | Component | The same props render the same markup, with no generated IDs, and states change properties and attributes, never elements | Open Components | Unit test | | `checkbox-group/data-attributes` | Should | Component | The size and the orientation are mirrored as `data-size` and `data-orientation`, and parts are marked with `data-slot` | Open Components | Unit test | | `checkbox-group/dev-warnings` | Should | Component | It warns during development when a group has no legend | Open Components | Unit test | # Checkbox Group Checkbox groups let people pick any number of options from a short list, like the emails they'd like to get, or the days they're free. Each box on its own is a [Checkbox](https://opencomponents.dev/docs/components/checkbox), and what goes wrong is usually what holds them together. Think of boxes that a screen reader announces one by one, without the question they answer, a "Select all" box that stays unchecked when every option is checked, or a form that says "This field is required" until you've checked every single box. This page walks you through building one the right way. We'll look at: ::card-group :::card --- icon: i-lucide-palette title: User Interface (UI) to: https://opencomponents.dev/docs/components/checkbox-group/ui --- How a checkbox group looks, from its parts, sizes and orientation to its states and tokens. ::: :::card --- icon: i-lucide-user title: User Experience (UX) to: https://opencomponents.dev/docs/components/checkbox-group/ux --- How a checkbox group behaves for every person, input and setting, so it's accessible, predictable, clear in every state and adaptive. ::: :::card --- icon: i-lucide-code-xml title: Developer Experience (DX) to: https://opencomponents.dev/docs/components/checkbox-group/dx --- How developers use the Checkbox Group, with one consistent, typed API that's built from Checkboxes and works with your forms however you build them. ::: :::card --- icon: i-lucide-bot title: Agentic Experience (AX) to: https://opencomponents.dev/docs/components/checkbox-group/ax --- How agents read, build and check a checkbox group, from its accessibility tree to its contract, its DOM and its tests. ::: :: ## At a glance Every example on this page runs on our [reference implementation](https://opencomponents.dev/docs/components/checkbox-group#reference-implementation), which does its part of every rule in the [checklist](https://opencomponents.dev/docs/components/checkbox-group#checklist), so feel free to check and uncheck them as you read. The code under each example comes in React, Vue, Svelte, Angular, Solid, Astro and Vanilla, written for a Checkbox Group with the same API in each. Pick yours from the Framework select above the sidebar. Vanilla is plain HTML and JavaScript, so it writes out the markup from the [DOM contract](https://opencomponents.dev/docs/components/checkbox-group/ax#deterministic). The Checkbox Group is a `
          ` of Checkboxes, so every rule on the [Checkbox](https://opencomponents.dev/docs/components/checkbox#checklist) page holds for each of its boxes, and this page covers what a group adds on top. Its hint and error message are elements of their own, which you link to it by ID, like the [Input](https://opencomponents.dev/docs/components/input)'s. :checkbox-group-playground | Aspect | Checkbox Group | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Element | `
          `, with a `` and a [Checkbox](https://opencomponents.dev/docs/components/checkbox) for each option | | Role | `group`, holding a `checkbox` for each option | | Name | The text of its `` | | Description | Its hint and its error message, linked with `aria-describedby` | | Value | A list of the checked options' values, sent with one shared `name` | | Keyboard | `Tab` reaches each checkbox in turn and `Space` checks or unchecks it, with no arrow keys | | States | Disabled and invalid, along with each checkbox's own, and a select-all box that can be mixed | | Sizes | `xs`, `sm`, `md`, `lg` and `xl`, the same as the Checkbox's | | Orientation | `vertical`, the default, or `horizontal` for two or three short options | | Pattern | [WAI-ARIA APG Checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/){rel=""nofollow""}, with its [mixed-state example](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/examples/checkbox-mixed/){rel=""nofollow""}, and the HTML [`
          `](https://html.spec.whatwg.org/multipage/form-elements.html#the-fieldset-element){rel=""nofollow""} | | WCAG 2.2 | 1.3.1, 1.4.10, 2.1.1, 3.3.1, 3.3.2, 3.3.3 and 4.1.2, among others | ## Checklist Here's every rule in one place, along with where it comes from and how to check it. A checkbox group meets the standard when it meets every **must**, and each **should** is expected unless you have a good reason not to follow it. Each of its boxes is a Checkbox, so the [Checkbox's checklist](https://opencomponents.dev/docs/components/checkbox#checklist) applies to every one of them as well, and the rules below only cover what the group adds. The scope says who meets a rule. **Component** rules are met by the Checkbox Group itself, so they're the ones to check when you build or review one. **Usage** rules are met by the forms that use it, like writing a legend that asks the question, so they're the ones to check when you review a screen. **Both** rules need the two to work together, like an invalid group: the Checkbox Group marks its boxes invalid from `aria-invalid`, as long as you set it when the error message shows. The basis says where a rule comes from. Many rules rest on **WCAG** 2.2, which we follow at level AA, and name the success criteria behind them, and a few come from **HTML** or the **APG**. The rest are **Open Components** rules, which are our own, like stacking options in a column. Where a rule goes further than WCAG asks at level AA, its basis says so with **beyond**. You'll find the rules for each layer on its page: - [User Interface (UI) Checklist](https://opencomponents.dev/docs/components/checkbox-group/ui#ui-checklist) - [User Experience (UX) Checklist](https://opencomponents.dev/docs/components/checkbox-group/ux#ux-checklist) - [Developer Experience (DX) Checklist](https://opencomponents.dev/docs/components/checkbox-group/dx#dx-checklist) - [Agentic Experience (AX) Checklist](https://opencomponents.dev/docs/components/checkbox-group/ax#ax-checklist) ## Reference implementation Our Vue 3 reference implementation does its part of every rule on this page, and powers every example on it. Feel free to copy it into your design system and change how it looks, but try to keep how it behaves. It's built out of the [Checkbox](https://opencomponents.dev/docs/components/checkbox#reference-implementation), which it imports from `../checkbox/Checkbox.vue`, so copy `Checkbox.vue` too. Both read the same theme tokens as the Button, so copy [`tokens.css`](https://opencomponents.dev/docs/components/button#reference-implementation) from the Button's reference implementation into your theme as well. The tests are in `CheckboxGroup.test.ts`. To run them, you'll need [Vitest](https://vitest.dev){rel=""nofollow""}, set to `environment: "jsdom"` and `globals: true`, along with `@testing-library/vue`, `@testing-library/user-event` and `@testing-library/jest-dom`. ::code-collapse :::code-group ```vue [CheckboxGroup.vue] ``` ```ts [CheckboxGroup.test.ts] import { render, screen, within } from "@testing-library/vue"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { h, nextTick, ref, type ComponentPublicInstance } from "vue"; import CheckboxGroup from "./CheckboxGroup.vue"; const options = [ { value: "cheese", label: "Cheese" }, { value: "mushrooms", label: "Mushrooms" }, { value: "olives", label: "Olives" }, ]; const toppings = () => "Toppings"; describe("CheckboxGroup", () => { it("is a fieldset, named by its legend, with a native checkbox for each option", () => { render(CheckboxGroup, { props: { name: "toppings", options }, slots: { default: toppings } }); const group = screen.getByRole("group", { name: "Toppings" }); expect(group).toHaveAccessibleName("Toppings"); expect(group.tagName).toBe("FIELDSET"); expect(group.firstElementChild?.tagName).toBe("LEGEND"); for (const { value, label } of options) { const checkbox = screen.getByRole("checkbox", { name: label }); expect(checkbox.tagName).toBe("INPUT"); // Only an invalid group marks its options invalid. expect(checkbox).not.toHaveAttribute("aria-invalid"); expect(checkbox).toHaveAttribute("name", "toppings"); expect(checkbox).toHaveAttribute("value", value); expect(group).toContainElement(checkbox); } }); it("is described by its hint and its error, through aria-describedby on the fieldset", () => { render({ render: () => [ h( CheckboxGroup, { name: "toppings", options, "aria-invalid": "true", "aria-describedby": "toppings-hint toppings-error" }, toppings, ), h("p", { id: "toppings-hint" }, "Pick as many as you like."), h("p", { id: "toppings-error" }, "Pick at least one topping"), ], }); const group = screen.getByRole("group", { name: "Toppings" }); expect(group).toHaveAttribute("aria-invalid", "true"); expect(group).toHaveAccessibleDescription("Pick as many as you like. Pick at least one topping"); // The boxes look and read invalid along with the group, while the message stays on the group. for (const { label } of options) { expect(screen.getByRole("checkbox", { name: label })).toHaveAttribute("aria-invalid", "true"); } }); it("is submitted with its form as one name, with a value for each checked option", async () => { const user = userEvent.setup(); const { container } = render({ render: () => h("form", [h(CheckboxGroup, { name: "toppings", options, selectAll: "All toppings" }, toppings)]), }); const form = container.querySelector("form")!; expect([...new FormData(form)]).toEqual([]); await user.click(screen.getByRole("checkbox", { name: "Olives" })); await user.click(screen.getByRole("checkbox", { name: "Cheese" })); // In the options' order, and without the select-all box, which has no name. expect(new FormData(form).getAll("toppings")).toEqual(["cheese", "olives"]); expect([...new FormData(form)]).toHaveLength(2); }); it("binds its value as a list with v-model, or keeps its own without it, starting from value", async () => { const user = userEvent.setup(); const picked = ref(["mushrooms"]); render({ render: () => [ h( CheckboxGroup, { name: "bound", options, value: picked.value, "onUpdate:value": (value: string[]) => (picked.value = value) }, () => "Bound", ), h(CheckboxGroup, { name: "unbound", options: [{ value: "yes", label: "Unbound option" }], value: ["yes"] }, () => "Unbound"), ], }); const bound = within(screen.getByRole("group", { name: "Bound" })); const cheese = bound.getByRole("checkbox", { name: "Cheese" }); const mushrooms = bound.getByRole("checkbox", { name: "Mushrooms" }); expect(mushrooms).toBeChecked(); await user.click(cheese); expect(picked.value).toEqual(["cheese", "mushrooms"]); picked.value = ["olives"]; await nextTick(); expect(cheese).not.toBeChecked(); expect(mushrooms).not.toBeChecked(); const unbound = screen.getByRole("checkbox", { name: "Unbound option" }); expect(unbound).toBeChecked(); await user.click(unbound); expect(unbound).not.toBeChecked(); }); it("keeps showing the value you hold when a bound change isn't taken", async () => { const user = userEvent.setup(); const onUpdate = vi.fn(); render(CheckboxGroup, { props: { name: "toppings", options, selectAll: "All toppings", value: ["cheese"], "onUpdate:value": onUpdate }, slots: { default: toppings }, }); const cheese = screen.getByRole("checkbox", { name: "Cheese" }); await user.click(cheese); expect(onUpdate).toHaveBeenCalledWith([]); await nextTick(); expect(cheese).toBeChecked(); const all = screen.getByRole("checkbox", { name: "All toppings" }); await user.click(all); expect(onUpdate).toHaveBeenLastCalledWith(["cheese", "mushrooms", "olives"]); await nextTick(); expect(all).toBePartiallyChecked(); expect(screen.getByRole("checkbox", { name: "Olives" })).not.toBeChecked(); }); it("is reached with Tab one checkbox at a time, each toggled with Space, with no arrow keys", async () => { const user = userEvent.setup(); render(CheckboxGroup, { props: { name: "toppings", options, selectAll: "All toppings" }, slots: { default: toppings } }); for (const name of ["All toppings", "Cheese", "Mushrooms", "Olives"]) { await user.tab(); expect(screen.getByRole("checkbox", { name })).toHaveFocus(); } await user.keyboard("{ArrowUp}"); expect(screen.getByRole("checkbox", { name: "Olives" })).toHaveFocus(); await user.keyboard(" "); expect(screen.getByRole("checkbox", { name: "Olives" })).toBeChecked(); await user.tab({ shift: true }); expect(screen.getByRole("checkbox", { name: "Mushrooms" })).toHaveFocus(); }); it("shows its select-all box checked, unchecked or mixed from its options, and checks or clears them all from it", async () => { const user = userEvent.setup(); const picked = ref([]); render({ render: () => h( CheckboxGroup, { name: "toppings", options, selectAll: "All toppings", value: picked.value, "onUpdate:value": (value: string[]) => (picked.value = value), }, toppings, ), }); const all = screen.getByRole("checkbox", { name: "All toppings" }); expect(all).not.toBeChecked(); expect(all).not.toBePartiallyChecked(); await user.click(screen.getByRole("checkbox", { name: "Cheese" })); await nextTick(); expect(all).toBePartiallyChecked(); // From mixed, it checks every option, rather than going back to an earlier selection. await user.click(all); await nextTick(); expect(picked.value).toEqual(["cheese", "mushrooms", "olives"]); expect(all).toBeChecked(); expect(all).not.toBePartiallyChecked(); // From checked, it clears them all. await user.click(all); await nextTick(); expect(picked.value).toEqual([]); expect(all).not.toBeChecked(); // From unchecked, it checks them all again. await user.click(all); await nextTick(); expect(picked.value).toEqual(["cheese", "mushrooms", "olives"]); // And it follows the options, whichever way they change. picked.value = ["olives"]; await nextTick(); expect(all).toBePartiallyChecked(); await user.click(screen.getByRole("checkbox", { name: "Olives" })); await nextTick(); expect(all).not.toBeChecked(); expect(all).not.toBePartiallyChecked(); }); it("can't be focused, changed or submitted while disabled, select-all box included", async () => { const user = userEvent.setup(); const { container } = render({ render: () => h("form", [ h( CheckboxGroup, { name: "toppings", options, selectAll: "All toppings", value: ["cheese"], disabled: true }, toppings, ), ]), }); const group = screen.getByRole("group", { name: "Toppings" }); expect(group).toBeDisabled(); await user.tab(); await user.click(screen.getByRole("checkbox", { name: "All toppings" })); await user.click(screen.getByText("Mushrooms")); expect(document.body).toHaveFocus(); for (const checkbox of screen.getAllByRole("checkbox")) expect(checkbox).toBeDisabled(); expect(screen.getByRole("checkbox", { name: "Mushrooms" })).not.toBeChecked(); expect([...new FormData(container.querySelector("form")!)]).toEqual([]); }); it("puts attributes, listeners and refs on the fieldset", async () => { const user = userEvent.setup(); const onChange = vi.fn(); const instance = ref>(); render({ render: () => h(CheckboxGroup, { ref: instance, id: "toppings", class: "toppings", name: "toppings", options, onChange }, toppings), }); const group = screen.getByRole("group", { name: "Toppings" }); expect(group).toHaveAttribute("id", "toppings"); expect(group).toHaveClass("checkbox-group", "toppings"); // Each checkbox's change bubbles up to the fieldset. await user.click(screen.getByRole("checkbox", { name: "Cheese" })); expect(onChange).toHaveBeenCalledTimes(1); expect(instance.value?.fieldset).toBe(group); }); it("is vertical by default, and mirrors its size and orientation as data attributes, with its size on every checkbox", () => { const { container } = render(CheckboxGroup, { props: { name: "toppings", options }, slots: { default: toppings } }); expect(container.firstElementChild).toHaveAttribute("data-orientation", "vertical"); expect(container.firstElementChild).toHaveAttribute("data-size", "md"); const { container: row } = render(CheckboxGroup, { props: { name: "toppings", options, size: "lg", orientation: "horizontal", selectAll: "All toppings" }, slots: { default: toppings }, }); const root = row.firstElementChild!; expect(root).toHaveAttribute("data-orientation", "horizontal"); expect(root).toHaveAttribute("data-size", "lg"); for (const checkbox of root.querySelectorAll(".checkbox")) expect(checkbox).toHaveAttribute("data-size", "lg"); }); it("renders the same markup every time, with its parts in a fixed order, across states", async () => { const props = { name: "toppings", options, selectAll: "All toppings" }; const first = render(CheckboxGroup, { props, slots: { default: toppings } }).container.innerHTML; const { container, rerender } = render(CheckboxGroup, { props, slots: { default: toppings } }); expect(container.innerHTML).toBe(first); const root = container.firstElementChild!; const parts = () => [...root.children].map((part) => part.getAttribute("data-slot")); expect(parts()).toEqual(["legend", "select-all", "options"]); const inputs = [...root.querySelectorAll("input")]; await rerender({ ...props, value: ["cheese"], disabled: true }); expect(container.firstElementChild).toBe(root); expect([...root.querySelectorAll("input")]).toEqual(inputs); expect(parts()).toEqual(["legend", "select-all", "options"]); }); it("warns in development when it has no legend", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); render(CheckboxGroup, { props: { name: "toppings", options } }); expect(warn).toHaveBeenCalledWith(expect.stringContaining("no accessible name"), expect.anything()); warn.mockClear(); render(CheckboxGroup, { props: { name: "toppings", options }, slots: { default: toppings } }); expect(warn).not.toHaveBeenCalled(); warn.mockRestore(); }); }); ``` ::: :: ## Sources - [HTML Standard: the fieldset element](https://html.spec.whatwg.org/multipage/form-elements.html#the-fieldset-element){rel=""nofollow""}, [the legend element](https://html.spec.whatwg.org/multipage/form-elements.html#the-legend-element){rel=""nofollow""}, [the checkbox state](https://html.spec.whatwg.org/multipage/input.html#checkbox-state-%28type%3Dcheckbox%29){rel=""nofollow""} and [constructing the form data set](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set){rel=""nofollow""}, for the group's name, `disabled`, what `required` means on a checkbox and what the form sends - [WAI-ARIA Authoring Practices Guide: Checkbox](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/){rel=""nofollow""}, for the select-all box's states and what checking and unchecking it does, and for describing a group with `aria-describedby` - [APG: Checkbox (Mixed-State) Example](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/examples/checkbox-mixed/){rel=""nofollow""}, for the `
          ` and `` around the options, and `Tab` between them - [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/){rel=""nofollow""} - [Understanding SC 1.3.1: Info and Relationships](https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html){rel=""nofollow""}, for grouping related controls under a name - [Understanding SC 3.3.2: Labels or Instructions](https://www.w3.org/WAI/WCAG22/Understanding/labels-or-instructions.html){rel=""nofollow""}, for saying when people have to pick one - [GOV.UK Design System: Checkboxes](https://design-system.service.gov.uk/components/checkboxes/){rel=""nofollow""}, for legends written as questions, hints like "Select all that apply", the order of the options and options given as data - [React Aria: CheckboxGroup](https://react-spectrum.adobe.com/react-aria/CheckboxGroup.html){rel=""nofollow""}, for the value as a list and a vertical or horizontal orientation # User Interface (UI) Let's start with how a checkbox looks: its parts, its sizes and how it shows each of its states. ## Anatomy ::checkbox-anatomy 1. **Container** — The `
          `, }) export class Shipping { countries = [ { value: "fr", label: "France" }, { value: "es", label: "Spain" }, { value: "nz", label: "New Zealand" }, ]; country = signal(undefined); } ``` #solid ```tsx import { createSignal } from "solid-js"; import { Combobox } from "~/components/Combobox"; import { Field } from "~/components/Field"; const countries = [ { value: "fr", label: "France" }, { value: "es", label: "Spain" }, { value: "nz", label: "New Zealand" }, ]; export function Shipping() { const [country, setCountry] = createSignal(); return ( setCountry(event.target.value)} /> ); } ``` #astro ```astro --- import Combobox from "../components/Combobox.astro"; import Field from "../components/Field.astro"; const countries = [ { value: "fr", label: "France" }, { value: "es", label: "Spain" }, { value: "nz", label: "New Zealand" }, ]; --- ``` #vanilla ```html
          France
          ``` :: ## Consistent The Combobox takes the Select's names wherever the two do the same thing, so moving a field from one to the other is a change of component, not of props: `options`, `multiple`, `placeholder`, the same `size` scale as the Input, `disabled`, `readonly`, `required`, `removeLabel` and `removedLabel`, and the Select's slots, `icon` included. Like the Select, classes and styles go on the root, `name` and `form` on the hidden ``, and leaves its form | | `readonly` | `boolean` | `false` | Keeps the value in its form, and doesn't open | | `required` | `boolean` | `false` | Asks for a value, and the Field sets it | | `allowCustomValue` | `boolean` | `false` | Keeps typed text as the value, for one value only | | `creatable` | `boolean` | `false` | Ends the list with an option that adds what people typed | | `createLabel` | `(text: string) => string` | `` `Create "${text}"` `` | The create option's label | | `filter` | `(option: SelectOption, text: string) => boolean` | Any part of the label, ignoring case and accents | Whether an option matches what people typed | | `emptyLabel` | `string` | `"No results"` | Shown and announced when nothing matches | | `resultsLabel` | `(count: number) => string` | `` `${count} results` ``, or "1 result" | Announced once typing pauses | | `toggleLabel` | `string` | `"Suggestions"` | The toggle button's name | | `removeLabel` | `(label: string) => string` | `` `Remove ${label}` `` | A tag's remove button's name | | `removedLabel` | `(label: string) => string` | `` `${label} removed` `` | What screen readers hear after a removal | | Event | Payload | Description | | -------- | -------- | ---------------------------------------------------------------------------------- | | `create` | `string` | People picked the create option, with the text they typed | | `change` | `Event` | Fires from the ``, and bubbles, right before `change` | | Slot | Gets | Description | | ------------- | ------------------------------ | ------------------------------------------------------------ | | `leading` | | An icon before the text, hidden from assistive technologies | | `arrow` | | The chevron in the toggle | | `option` | `option`, `selected`, `active` | How an option reads. The check mark stays beside it | | `tag` | `option` | How a picked value reads in its tag. The remove button stays | | `group-label` | `label` | How a group's heading reads | | `separator` | | The rule between options or groups | | `icon` | `option` | An option's icon, in the panel, the field and its tag | React and Solid take `groupLabel` for the `group-label` slot and `onCreate` for the event, and Angular binds `(create)`, each in its own idiom. Import the types from the Select, where they live, so a list typed for one works for both: ::framework-switcher #react ```tsx import type { SelectItem } from "@/components/Select"; import type { ComboboxProps } from "@/components/Combobox"; const countries: SelectItem[] = [ { value: "fr", label: "France" }, { value: "nz", label: "New Zealand" }, ]; ``` #vue ```vue ``` #svelte ```svelte ``` #angular ```angular-html import type { SelectItem } from "./select"; import type { ComboboxProps } from "./combobox"; const countries: SelectItem[] = [ { value: "fr", label: "France" }, { value: "nz", label: "New Zealand" }, ]; ``` #solid ```tsx import type { SelectItem } from "~/components/Select"; import type { ComboboxProps } from "~/components/Combobox"; const countries: SelectItem[] = [ { value: "fr", label: "France" }, { value: "nz", label: "New Zealand" }, ]; ``` #astro ```astro --- import type { SelectItem } from "../components/Select.astro"; const countries: SelectItem[] = [ { value: "fr", label: "France" }, { value: "nz", label: "New Zealand" }, ]; --- ``` #vanilla ```html ``` :: ## Composable Put the Combobox in a [Field](https://opencomponents.dev/docs/components/field), and it gets its label, hint, error, `required`, `disabled` and `size` without any wiring. It takes the same text-control path through the Field as an Input and a Select do. The slots let you change what's inside each part without giving up how it behaves. The `option` slot keeps the check mark beside what you render, and the `tag` slot keeps the remove button. Here's an option that shows the country's code beside its name: ::framework-switcher #react ```tsx } option={({ option, selected }) => <>{option.label} {option.value.toUpperCase()}{selected && " (yours)"}} /> ``` #vue ```vue ``` #svelte ```svelte {#snippet leading()}{/snippet} {#snippet option({ option, selected })} {option.label} {option.value.toUpperCase()}{selected ? " (yours)" : ""} {/snippet} ``` #angular ```angular-html
          {{ option.label }} {{ option.value.toUpperCase() }}@if (selected) { (yours)}
          ``` #solid ```tsx } option={({ option, selected }) => <>{option.label} {option.value.toUpperCase()}{selected && " (yours)"}} /> ``` #astro ```astro {({ option, selected }) => <>{option.label} {option.value.toUpperCase()}{selected && " (yours)"}} ``` #vanilla ```html
          France FR
          ``` :: ## Controllable Bind the value when your code reads it, and leave it unbound when the form is all you need. The `
          ``` #solid ```tsx {/* Controlled: your state decides. */} setCountry(event.target.value)} /> {/* Uncontrolled: the Combobox keeps its own, and its form submits it. */} {/* New values: add them to your list as people create them. */} setTopics([...topics(), { value: text, label: text }])} /> ``` #astro ```astro ``` #vanilla ```html ``` :: `change` and `input` fire from the ``, through `control` and `select`, for focusing it from your own code. ## DX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ------------------------ | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------- | | `combobox/select-names` | Should | Component | It takes the Select's names for what the two share: `options`, `multiple`, `size`, `placeholder`, `disabled`, `readonly`, `required` and the slots | Open Components | Review | | `combobox/typed` | Must | Component | Its props, events and slots are typed, and it takes the Select's exported option types | Open Components | Type check | | `combobox/value` | Must | Component | The value is a string, or an array with `multiple`, bound or unbound from a `value` attribute, and the text follows a bound value as it changes | Open Components | Unit test | | `combobox/native-events` | Should | Component | `change` and `input` fire from its ``, and `id`, ARIA and `autocomplete` on the text field | Open Components | Unit test | | `combobox/in-a-field` | Must | Both | In a Field, it takes the label, description, invalid and disabled state | WCAG 1.3.1 (A) | Unit test | | `combobox/slots` | Should | Component | Each part has a slot or tokens to restyle it, and the check mark and remove button stay | Open Components | Unit test | | `combobox/create-event` | Must | Component | Picking the create option fires `create` with the text people typed | Open Components | Unit test | | `combobox/custom-filter` | Should | Component | A `filter` prop replaces how options match what people typed | Open Components | Unit test | | `combobox/translatable` | Should | Component | Every string it shows or announces comes through a prop | Open Components | Unit test | | `combobox/exposed` | Should | Component | A ref gets the text field and the `
          France
        7. ``` - The panel is the Select's, with the same markup, apart from `popover="manual"`, since a press in the text mustn't close it, and the Combobox closes it on a press outside the field instead. - The panel's ID is the text field's `id`, or its `name`, with `-panel` on the end, and option IDs add `-option-` and their position in the whole list, so an option keeps its ID as the list narrows, and a screen reader hears each new highlight. The create option's ID ends in `-option-create`. - States change attributes, never elements, apart from the tags, which come and go with the values, and the options, which come and go as people type. - Once it mounts, the root gets `anchor-name` and the panel `position-anchor` in its `style`, from your framework's ID helper. While an on-screen keyboard is up, or in browsers without CSS anchor positioning, an open panel also gets `top`, `left` and `width`, and `data-fit="visual"` while the keyboard is up. ## Verifiable Every rule in the checklist can be checked, and most of them automatically. ### Unit tests Every rule that the checklist checks with a unit test has one in `Combobox.test.ts`, which you'll find under [Reference implementation](https://opencomponents.dev/docs/components/combobox#reference-implementation). We run them on every change to this page, so the code you see always passes them. They run in jsdom, so the tests stand in for the Popover API, `scrollIntoView`, `requestSubmit` and the visual viewport. Placing the panel against the real on-screen keyboard only happens on a phone, and anchor positioning only in a browser, so check those there. ### In the browser You can use the keyboard and the pointer the way people would, and run [axe](https://github.com/dequelabs/axe-core){rel=""nofollow""} over the open panel, with and without a match: ```ts import AxeBuilder from "@axe-core/playwright"; import { expect, test } from "@playwright/test"; test("the Country combobox filters, picks and keeps what people chose", async ({ page }) => { await page.goto("/shipping"); const country = page.getByRole("combobox", { name: "Country" }); await country.fill("zeal"); await expect(country).toHaveAttribute("aria-expanded", "true"); await expect(country).not.toHaveAttribute("aria-activedescendant"); const { violations } = await new AxeBuilder({ page }) .withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]) .analyze(); expect(violations).toEqual([]); await page.keyboard.press("ArrowDown"); await page.keyboard.press("Enter"); await expect(country).toHaveValue("New Zealand"); await expect(country).toBeFocused(); }); ``` Some things still need a human, so try your Comboboxes near every edge of the window and on a real phone with its keyboard up, check that the panel flips and fits, and use them with a screen reader, on Windows and on macOS, listening for the count as you type. Try them at 200% zoom and with forced colours, more contrast and reduced motion turned on too. You can emulate the last three in Chrome DevTools, under Rendering. ### During development Our reference implementation also warns you in the console when a Combobox renders without a name, without the `id` or `name` that its panel and options need, or with `allowCustomValue` and `multiple` together, which does nothing. ### Prompts You can point your agent straight at this page. To build a combobox, you could use: ::framework-switcher #react ```text Build a Combobox component for our React design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vue ```text Build a Combobox component for our Vue 3 design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #svelte ```text Build a Combobox component for our Svelte 5 design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #angular ```text Build a Combobox component for our Angular design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #solid ```text Build a Combobox component for our Solid design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #astro ```text Build a Combobox component for our Astro design system that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its API, its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` #vanilla ```text Build a Combobox for our design system in plain HTML, CSS and JavaScript that meets the Open Components Combobox standard: https://opencomponents.dev/raw/docs/components/combobox.md Follow its DOM contract and its tokens. Port its tests and make them pass. Then check your work against every rule in its checklist with a Component or Both scope, and cite the rule ID for any rule you can't meet. ``` :: To review one, the contract is enough: ```text Review our Combobox against the Open Components Combobox contract: https://opencomponents.dev/raw/docs/components/combobox.yaml For each rule with a component or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` And to review how a screen uses its comboboxes: ```text Review how our shipping page uses its comboboxes against the Open Components Combobox contract: https://opencomponents.dev/raw/docs/components/combobox.yaml For each rule with a usage or both scope, report pass or fail with the rule ID and the evidence from our code. Then fix the failures. ``` ## AX Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ---------------------------- | ------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------ | | `combobox/role-and-name` | Must | Component | It can be found with `getByRole("combobox", { name })`, and its options with `getByRole("option", { name })` | WCAG 4.1.2 (A) | Unit test, ARIA snapshot | | `combobox/deterministic-dom` | Must | Component | The same props render the same markup, every ID is made from its own `id` or `name`, and options keep their IDs as the list narrows | Open Components | Unit test | | `combobox/data-attributes` | Should | Component | Its state and size are mirrored as `data-state` and `data-size`, and parts are marked with `data-slot` | Open Components | Unit test | | `combobox/dev-warnings` | Should | Component | It warns during development when it has no name, no `id` or `name`, or `allowCustomValue` with `multiple` | Open Components | Unit test | # Combobox Comboboxes let people type into a text field to narrow a long list of suggestions and pick one, like a country, a city or the people to share a file with. They're also where a text field, a popover and a list most often fall out of step. Think of a list that picks the first match when people press `Enter`, so "Fra" quietly becomes France, a screen reader that hears nothing while the list empties as people type, or a phone's keyboard that slides up over the half of the list people were about to tap. This page walks you through building one the right way. We'll look at: ::card-group :::card --- icon: i-lucide-palette title: User Interface (UI) to: https://opencomponents.dev/docs/components/combobox/ui --- How a combobox looks, from its parts and its sizes to one or several values, its states and the tokens it shares with the Select. ::: :::card --- icon: i-lucide-user title: User Experience (UX) to: https://opencomponents.dev/docs/components/combobox/ux --- How a combobox behaves for every person, input and setting, from the ARIA pattern and the keyboard to filtering, typed values, forms and the on-screen keyboard. ::: :::card --- icon: i-lucide-code-xml title: Developer Experience (DX) to: https://opencomponents.dev/docs/components/combobox/dx --- How developers use the Combobox, with the Select's typed list of options, opt-in props for typed values and a slot for each part. ::: :::card --- icon: i-lucide-bot title: Agentic Experience (AX) to: https://opencomponents.dev/docs/components/combobox/ax --- How agents read, operate and check a combobox, from its accessibility tree to its contract, its DOM and its tests. ::: :: ## At a glance Every example on this page runs on our [reference implementation](https://opencomponents.dev/docs/components/combobox#reference-implementation), which does its part of every rule in the [checklist](https://opencomponents.dev/docs/components/combobox#checklist), so feel free to open them as you read. The code under each example comes in React, Vue, Svelte, Angular, Solid, Astro and Vanilla, written for a Combobox with the same API in each, apart from a few names in React, Solid and Angular, which [Type-safe](https://opencomponents.dev/docs/components/combobox/dx#type-safe) explains. Pick yours from the Framework select above the sidebar. Vanilla is plain HTML and JavaScript, so it writes out the markup from the [DOM contract](https://opencomponents.dev/docs/components/combobox/ax#deterministic). The Combobox builds on the [Select](https://opencomponents.dev/docs/components/select) for its panel, its options, its groups, its tags and the tokens that style them, on the [Popover](https://opencomponents.dev/docs/components/popover) for where the panel opens and how it flips, on the [Input](https://opencomponents.dev/docs/components/input) for how the text field looks and on the [Field](https://opencomponents.dev/docs/components/field) for its label, hint and error. It's a component of its own, rather than a mode of the Select, since typing changes what `Space`, letters, `Home` and `End` do, brings up the on-screen keyboard and can produce a value that isn't an option. :combobox-playground | Aspect | Combobox | | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Element | A `
          ` that draws the field, holding an ``, a hidden ``, with `aria-autocomplete="list"` and a `listbox` popup of options | | Name | The Field's `
          ``` ::: :: A [Textarea](https://opencomponents.dev/docs/components/textarea) with a `limit` shows its count right under the box, before the Field's error, and adds it to its description after the Field's hint and error, so people hear what the field asks for before how many characters they have left. The Field takes a native ``, `
          ``` #solid ```tsx
          ``` ::: :: | Size | One row | Text | Line height | Padding | Radius | | ---- | ------- | ---- | ----------- | ------- | ------ | | `xs` | 24px | 12px | 18px | 8px | 6px | | `sm` | 32px | 14px | 21px | 10px | 6px | | `md` | 36px | 14px | 21px | 12px | 8px | | `lg` | 40px | 16px | 24px | 14px | 8px | | `xl` | 48px | 16px | 24px | 16px | 12px | Sizes are set in `rem`, and the table shows the values we recommend at the default text size of 16px. The line height is 1.5 times the text, a little more than the Input's, since people read what they've written back over several lines. The padding above and below the text is whatever's left of one row's height, so every size meets the 24 × 24px minimum from [WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html){rel=""nofollow""}. On touch screens, the text grows to at least 16px, since Safari on iOS zooms in on a textarea with smaller text as soon as it gets focus, and the field is at least 44px tall, whatever its rows. ## Height A textarea's height says how much people are expected to write, just like an input's width. `rows` sets how many lines it shows, and it's never shorter than that, so it's the first thing to pick. From there, the height can go one of two ways. Either people resize it, by dragging the handle in its corner, or it grows with its text, with `autoGrow`, up to `maxRows`. ::textarea-height-example :::framework-switcher #react ```tsx
        8. ``` #solid ```tsx

          ``` ::: :: - Pick `rows` for the text you expect, so people can see all of it as they write. Three rows suit a short note, while a message or a description might need five or more. A box that's too small makes people scroll inside it to check what they wrote, which is hard for everyone and harder still at 200% zoom. - A resizable textarea only resizes on the block axis, taller or shorter, since a textarea that gets wider than its column breaks the layout around it ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html){rel=""nofollow""}). It never gets shorter than its `rows`. - An auto-growing textarea has no handle, since there's nothing left for people to resize. It grows with [`field-sizing: content`](https://developer.mozilla.org/en-US/docs/Web/CSS/field-sizing){rel=""nofollow""} where the browser supports it, and elsewhere the Textarea sets its height from a script as people type. - Give an auto-growing textarea a `maxRows`, so that a long text doesn't push the rest of the form, and its submit button, off the screen. Past it, the text scrolls inside the field. - We recommend letting it fill the width of its column, since lines that run the whole width of a wide screen are hard to read back, and a narrow textarea wraps them short. Set its width from a class if the column is wider than 80 characters, which is as wide as a block of text should get ([WCAG 1.4.8](https://www.w3.org/WAI/WCAG22/Understanding/visual-presentation.html){rel=""nofollow""}). ## Character count When there's a limit on how much people can write, like a bio for a profile or a message to a support team, `limit` shows a count under the field. It says how many characters are left, and once people go over, how many too many. We recommend saying what the limit is in the hint too, so people know it before they start. ::textarea-count-example :::framework-switcher #react ```tsx

          You can enter up to 160 characters

``` #solid ```tsx

You can enter up to 160 characters

160 characters left ``` ::: :: - The count never stops people typing or pasting, unlike `maxlength`. Over the limit, it turns red, says by how much, and marks the textarea invalid, so people can decide what to cut (see [Don't cut people off](https://opencomponents.dev/docs/components/textarea/ux#dont-cut-people-off)). - The count describes the textarea, after any hint, so screen readers read it when the textarea gets focus. As people near the limit, it's also announced once they pause typing, rather than on every keystroke. - The count is named after the textarea's `id`, as in `bio-count`, so give every textarea with a limit an `id`, which its label needs anyway. - The count's text is in English. To write it in the page's language, pass `countLabel`, which gets the number of characters left, and a negative number over the limit. ## States Each state has a look of its own, styled from the attribute on the `

Enter a reason for returning the item

``` #solid ```tsx

Enter a reason for returning the item

``` ::: :: | State | Selector | Recommended look | | --------- | ---------------------------------------- | --------------------------------------------------------------------------- | | Hover | `:hover`, inside `@media (hover: hover)` | The border at 80% of the text colour, up from 55% | | Focus | `:focus-visible` | A 2px outline, 2px from the edge, in `--color--focus` | | Disabled | `:disabled` | 50% opacity, for the count too, a `not-allowed` cursor and no resize handle | | Read-only | `[readonly]` | A dashed border, with the text at full contrast, and the default cursor | | Invalid | `[aria-invalid="true"]` | A 2px border in `--color--error-text` | The ` `, styles: ` .soft { --textarea--radius: 1rem; } `, }) export class Feedback {} ``` #solid ```tsx [Feedback.tsx] import styles from "./Feedback.module.css"; export function Feedback() { return ( <> ``` :: ## UI Checklist | Rule | Level | Scope | Requirement | Basis | Check | | ---------------------------- | ------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | -------------------------------------- | | `textarea/contrast` | Must | Component | The text, the placeholder and the count have a contrast of 4.5:1, and the focus ring has 3:1 against the page | WCAG 1.4.3, 1.4.11 (AA) | axe `color-contrast`, contrast checker | | `textarea/boundary-contrast` | Must | Component | The border has a contrast of 3:1 against the page, so an empty textarea stays visible | WCAG 1.4.11 (AA) | Contrast checker | | `textarea/focus-visible` | Must | Component | Focus shows an `outline` at least 2px thick around the field, outside its border | WCAG 2.4.7 (AA), 2.4.13 (AAA) | Keyboard | | `textarea/target-size` | Must | Component | The field is at least 24px tall, and at least 44px tall on touch screens | WCAG 2.5.8 (AA), 2.5.5 (AAA) | Emulation | | `textarea/no-zoom-on-focus` | Should | Component | On touch screens, the text is at least 16px, so Safari on iOS doesn't zoom in when the textarea gets focus | Open Components | Emulation | | `textarea/min-rows` | Must | Component | It's never shorter than its `rows`, whether people resize it or it grows on its own | Open Components | Visual regression test | | `textarea/resizable` | Must | Component | Its height is a minimum, in lines of its own line height plus padding in `rem`, so it grows with its text instead of clipping it | Open Components, beyond WCAG 1.4.4, 1.4.12 (AA) | 200% zoom | | `textarea/block-resize` | Should | Component | People resize it on the block axis only, and resizing is only turned off when it grows on its own or is disabled | Open Components | Visual regression test | | `textarea/auto-grow` | Should | Component | With `autoGrow`, it grows with its text up to `maxRows`, then scrolls, with `field-sizing: content` or a script where that's not supported | Open Components | Visual regression test, 200% zoom | | `textarea/stable-size` | Must | Component | No state changes the field's size or position | Open Components | Visual regression test | | `textarea/state-selectors` | Should | Component | States are styled from the attributes on the `
``` #svelte ```svelte
``` #angular ```angular-html
``` #solid ```tsx {/* Do: you get editing, new lines, autofill and form submission for free */}
``` #vanilla ```html
``` :: If people need formatting, like bold text and lists, that's a rich text editor, which is a different component with a lot more to it. For plain text, keep to the ` ``` #solid ```tsx

Include what you were doing, and any error message you saw

``` ::: :: - Every textarea has a visible `