Menu

Components

Kbd

A key of the keyboard, or a shortcut of several, shown as keycaps.

Introduction

Kbd shows what to press: a key, or the keys of a shortcut, as keycaps. Use it in text that tells people how to do something, and next to a command that has a shortcut.

  • Give a key as text, or give keys by name and it is drawn for the platform of the person: mod is ⌘ on a Mac and Ctrl elsewhere, option is ⌥ or Alt.
  • A screen reader reads the keys in words ("Command, Shift, P" on a Mac, "Control, Shift, P" elsewhere), not as symbols.
  • A word or a plus sign between keys, three looks, three sizes, and it is an inline element, so it sits in a sentence.
  • It only shows the keys: it does not listen for them. For a shortcut that works, listen for it yourself, and show it here.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles, the key names and the platform hook

src/types/kbd-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Kbd. The keycap is drawn with a border that is thicker at the
// bottom, as the edge of a key; the ghost variant is only the text.
export const kbdStyles = tv({
  slots: {
    root: "inline-flex items-center gap-1 align-baseline",
    key: "inline-flex items-center justify-center rounded-md font-sans font-medium leading-none whitespace-nowrap tabular-nums select-none",
    separator: "text-muted-fg",
  },
  variants: {
    variant: {
      outline: {
        key: "border border-b-2 bg-muted text-fg",
      },
      solid: {
        key: "bg-fg text-bg",
      },
      ghost: {
        key: "px-0.5 text-muted-fg",
      },
    },
    size: {
      sm: { key: "h-5 min-w-5 px-1 text-[10px]", separator: "text-[10px]" },
      md: { key: "h-6 min-w-6 px-1.5 text-xs", separator: "text-xs" },
      lg: { key: "h-7 min-w-7 px-2 text-sm", separator: "text-sm" },
    },
    // A pill instead of a keycap's own corners. It is after `size` so it wins
    // over the smaller radius, and pairs well with `combined`, whose symbols
    // already give the shape room to be round.
    isCircle: {
      true: { key: "rounded-full" },
      false: {},
    },
  },
  compoundVariants: [
    // A pill wants a little more room at its ends than a square keycap.
    { isCircle: true, size: "sm", class: { key: "px-2" } },
    { isCircle: true, size: "md", class: { key: "px-2.5" } },
    { isCircle: true, size: "lg", class: { key: "px-3.5" } },
  ],
  defaultVariants: { variant: "outline", size: "md", isCircle: false },
});
src/types/kbd-keys.tsShow code
// The names of keys that `Kbd` knows, and how each is written. A name can be
// written in any case. Anything else, such as "k" or "F5", is written as it is,
// in capitals.

export interface KbdKey {
  /** What is drawn, on a Mac and elsewhere. */
  mac: string;
  other: string;
  /** What a screen reader says, on a Mac and, when it differs, elsewhere. */
  label: string;
  otherLabel?: string;
  /** Other names that mean the same key. */
  aliases?: string[];
}

export const kbdKeys: Record<string, KbdKey> = {
  // `mod` is the key of shortcuts: Command on a Mac, Control elsewhere.
  mod: { mac: "⌘", other: "Ctrl", label: "Command", otherLabel: "Control" },
  command: {
    mac: "⌘",
    other: "Win",
    label: "Command",
    aliases: ["cmd", "meta"],
  },
  control: { mac: "⌃", other: "Ctrl", label: "Control", aliases: ["ctrl"] },
  option: {
    mac: "⌥",
    other: "Alt",
    label: "Option",
    otherLabel: "Alt",
    aliases: ["alt"],
  },
  shift: { mac: "⇧", other: "Shift", label: "Shift" },
  enter: { mac: "↵", other: "Enter", label: "Enter", aliases: ["return"] },
  backspace: { mac: "⌫", other: "Backspace", label: "Backspace" },
  delete: { mac: "⌦", other: "Del", label: "Delete", aliases: ["del"] },
  escape: { mac: "⎋", other: "Esc", label: "Escape", aliases: ["esc"] },
  tab: { mac: "⇥", other: "Tab", label: "Tab" },
  space: { mac: "␣", other: "Space", label: "Space" },
  capslock: { mac: "⇪", other: "Caps", label: "Caps Lock" },
  up: { mac: "↑", other: "↑", label: "Up arrow", aliases: ["arrowup"] },
  down: { mac: "↓", other: "↓", label: "Down arrow", aliases: ["arrowdown"] },
  left: { mac: "←", other: "←", label: "Left arrow", aliases: ["arrowleft"] },
  right: {
    mac: "→",
    other: "→",
    label: "Right arrow",
    aliases: ["arrowright"],
  },
  pageup: { mac: "⇞", other: "PgUp", label: "Page Up" },
  pagedown: { mac: "⇟", other: "PgDn", label: "Page Down" },
  home: { mac: "↖", other: "Home", label: "Home" },
  end: { mac: "↘", other: "End", label: "End" },
  fn: { mac: "fn", other: "Fn", label: "Function" },
};

const byName = new Map<string, KbdKey>();
for (const [name, key] of Object.entries(kbdKeys)) {
  byName.set(name, key);
  for (const alias of key.aliases ?? []) byName.set(alias, key);
}

/** How a key is drawn and read out, for a name such as `"cmd"` or `"k"`. */
export function resolveKey(name: string, isMac: boolean) {
  const known = byName.get(name.trim().toLowerCase());
  if (known)
    return {
      text: isMac ? known.mac : known.other,
      label: isMac ? known.label : (known.otherLabel ?? known.label),
    };
  // Letters and function keys are written in capitals: k is K, f4 is F4.
  const text =
    name.length === 1 || /^f\d{1,2}$/i.test(name) ? name.toUpperCase() : name;
  return { text, label: text };
}
src/types/use-is-mac.tsShow code
import { useSyncExternalStore } from "react";

/**
 * Whether this is a Mac, an iPhone or an iPad, where the command key is written
 * ⌘ and not Ctrl. It is `false` on the server and while the page hydrates, and
 * `true` after if it is one, so that the page is the same on both sides.
 */
export function useIsMac() {
  return useSyncExternalStore(
    () => () => {},
    () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent),
    () => false,
  );
}

2. Add the Kbd file

src/components/ui/kbd/kbd.tsxShow code
"use client";

import { Fragment, type ReactNode } from "react";
import { cn } from "@/lib/cn";
import { resolveKey } from "@/types/kbd-keys";
import { kbdStyles } from "@/types/kbd-styles";
import { useIsMac } from "@/types/use-is-mac";

export interface KbdProps {
  /**
   * The key, or the keys of a shortcut, by name: `"k"`, `"enter"`, `["mod",
   * "shift", "p"]`. Names such as `mod` (Command on a Mac, Control elsewhere),
   * `shift`, `option` and `escape` are drawn as the key is written on the
   * platform of the person, and read out in full. See `kbdKeys` for the list.
   */
  keys?: string | string[];
  /** What to draw for one key, as it is written, when a name will not do. Use it or `keys`. */
  children?: ReactNode;
  /** What goes between the keys of a shortcut: `"+"` for keys pressed together, `"then"` for keys pressed one after the other. Nothing by default. */
  separator?: ReactNode;
  /**
   * Draw the keys as one keycap, as they are written in menus: ⌘K, ⌘⇧P on a Mac
   * and Ctrl+K, Ctrl+Shift+P elsewhere. Without it each key has a keycap of its
   * own. `separator` then sets what goes between the keys, in place of the usual.
   */
  combined?: boolean;
  /** The look: a keycap, a solid key, or only the text. Defaults to `outline`. */
  variant?: "outline" | "solid" | "ghost";
  size?: "sm" | "md" | "lg";
  /** A pill instead of a keycap's own corners. Pairs well with `combined`. Defaults to `false`. */
  isCircle?: boolean;
  /** Draw the keys of one platform on every platform: `mac` for ⌘ ⇧ ⌥, `other` for Ctrl Shift Alt. Defaults to the platform of the person. */
  platform?: "auto" | "mac" | "other";
  className?: string;
}

/**
 * A key of the keyboard, or a shortcut of several: what to press, shown as
 * keycaps. Use it in text that tells people how to do something, and next to a
 * command that has a shortcut. It only shows the keys: it does not listen for
 * them.
 *
 * Names are drawn for the platform of the person (⌘ on a Mac, Ctrl elsewhere
 * for `mod`) and a screen reader reads the whole shortcut in words ("Command,
 * Shift, P"), not the symbols. It is an inline element, so it can sit in
 * a sentence.
 *
 * @example
 * Press <Kbd keys={["mod", "k"]} /> to search.
 */
export function Kbd({
  keys,
  children,
  separator,
  combined = false,
  variant,
  size,
  isCircle = false,
  platform = "auto",
  className,
}: KbdProps) {
  const detectedMac = useIsMac();
  const isMac = platform === "auto" ? detectedMac : platform === "mac";
  const styles = kbdStyles({ variant, size, isCircle });

  // One key, written as the caller wants it.
  if (keys === undefined) {
    return <kbd className={cn(styles.key(), className)}>{children}</kbd>;
  }

  const names = Array.isArray(keys) ? keys : [keys];
  const resolved = names.map((name) => resolveKey(name, isMac));

  // All the keys in one keycap. A Mac writes them next to each other (⌘⇧P), as
  // long as each is a symbol or a letter; others put a plus between them.
  if (combined) {
    const joiner =
      separator ??
      (isMac && resolved.every((key) => key.text.length <= 2) ? "" : "+");
    return (
      <kbd className={cn(styles.key(), className)}>
        <span aria-hidden="true">
          {resolved.map((key) => key.text).join(String(joiner))}
        </span>
        <span className="sr-only">
          {resolved.map((key) => key.label).join(", ")}
        </span>
      </kbd>
    );
  }

  return (
    <span className={cn(styles.root(), className)}>
      {resolved.map((key, index) => (
        // biome-ignore lint/suspicious/noArrayIndexKey: the keys are the positions; the same key can be twice
        <Fragment key={index}>
          {index > 0 && separator ? (
            <span aria-hidden="true" className={styles.separator()}>
              {separator}
            </span>
          ) : null}
          <kbd className={styles.key()}>
            <span aria-hidden="true">{key.text}</span>
            <span className="sr-only">
              {key.label}
              {index < resolved.length - 1 ? "," : ""}
            </span>
          </kbd>
        </Fragment>
      ))}
    </span>
  );
}

3. Use it

import { Kbd } from "@/components/ui/kbd/kbd";

Anatomy

One key, or a group of them.

<Kbd>K</Kbd>
<Kbd keys="enter" />
<Kbd keys={["mod", "shift", "p"]} separator="+" size="lg" />
PartRendered asNotes
KeykbdOne key, drawn as a keycap. What it holds is hidden from a screen reader, which reads the name of the key instead.
GroupspanAround the keys of a shortcut, with what goes between them (a plus sign, a word). It is only there when you give keys.

Examples

Usage

Give one key as text, written as you like.

KEscF5

Shortcuts

keys by name. Each is drawn as it is written on the platform of the person: on a Mac ⌘ ⇧ ⌥, elsewhere Ctrl Shift Alt.

Control,KControl,Shift,PAlt,Enter

Combined

combined draws the keys as one keycap, as they are written in menus: on a Mac the symbols next to each other (⌘K), elsewhere with a plus between them (Ctrl+K). The screen reader still reads each key.

Control, KControl, Shift, PAlt, Enter
Mac Command, KCommand, Shift, PWindows Control, KControl, Shift, P

With a plus

A plus sign is how a shortcut is written in text and in most Windows apps, and works for a Mac too: give separator a value and it is used instead of the usual join, on every platform.

Control, KControl, Shift, PControl, Alt, Enter
MacCommand, KCommand, Shift, PWindowsControl, KControl, Alt, Delete

Pill

isCircle rounds a keycap into a pill instead of its own corners. It pairs well with combined, whose two or three symbols already give the shape room to be round.

Control, KControl, Shift, P
Control, KControl, KControl, K

Mac and Windows

Common shortcuts, side by side. When the shortcut is the same with the command key of the platform, use mod and give the same keys to both. When it is not, give each platform its own.

ActionMacWindows
CopyCommand,CControl,C
PasteCommand,VControl,V
UndoCommand,ZControl,Z
RedoCommand,Shift,ZControl,Y
Select allCommand,AControl,A
FindCommand,FControl,F
SaveCommand,SControl,S
Command menuCommand,KControl,K
Command paletteCommand,Shift,PControl,Shift,P
New tabCommand,TControl,T
Close tabCommand,WControl,W
Reopen closed tabCommand,Shift,TControl,Shift,T
Switch appCommand,TabAlt,Tab
Quit the appCommand,QAlt,F4
Force quitCommand,Option,EscapeControl,Shift,Escape
Delete forwardFunction,BackspaceDelete
Lock the screenControl,Command,QCommand,L
ScreenshotCommand,Shift,4Command,Shift,S

Separators

Something between the keys: a plus sign for keys pressed together, or a word for keys pressed one after the other.

Control,KG,H

Platform

The keys follow the platform of the person. Set platform to draw one platform's keys everywhere, such as in a document about Windows.

autoControl,Shift,P
macCommand,Shift,P
otherControl,Shift,P

In text

It is an inline element and takes the height of a line of text at size sm.

Press Control,K to search, or / to focus the field. To close a panel press Escape.

Variants

Control,KControl,KControl,K

Sizes

Control,KControl,KControl,K

In a button

The ghost variant at size sm fits at the end of a button.

Arrows

Up arrowDown arrowLeft arrowRight arrow

Key names

The names that keys knows, in any case. Anything else, such as k or F5, is drawn as it is, in capitals.

NameMacElsewhereRead out as
mod⌘CtrlCommand, or Control elsewhere
command, cmd, meta⌘WinCommand
control, ctrl⌃CtrlControl
option, alt⌥AltOption, or Alt elsewhere
shift⇧ShiftShift
enter, return↵EnterEnter
backspace⌫BackspaceBackspace
delete, del⌦DelDelete
escape, esc⎋EscEscape
tab⇥TabTab
space␣SpaceSpace
capslock⇪CapsCaps Lock
up, arrowup↑↑Up arrow
down, arrowdown↓↓Down arrow
left, arrowleft←←Left arrow
right, arrowright→→Right arrow
pageup⇞PgUpPage Up
pagedown⇟PgDnPage Down
home↖HomeHome
end↘EndEnd
fnfnFnFunction

Component API

Kbd takes the props below.

PropTypeDefault
keysstring | string[]-
childrenReactNode-
separatorReactNode-
combinedbooleanfalse
variant"outline" | "solid" | "ghost""outline"
size"sm" | "md" | "lg""md"
isCirclebooleanfalse
platform"auto" | "mac" | "other""auto"
classNamestring-