# Layout & spacing

A 4px grid, space that grows with the distance between ideas, and one breakpoint between a phone and the rest.

API [useMediaQuery](/ui/storybook/?path=/docs/ui-hooks-usemediaquery--docs) [Card](/ui/storybook/?path=/docs/ui-primitives-card--docs) [Frame](/ui/storybook/?path=/docs/ui-primitives-frame--docs) [Pane](/ui/storybook/?path=/docs/ui-primitives-pane--docs) [Separator](/ui/storybook/?path=/docs/ui-primitives-separator--docs) [Sheet](/ui/storybook/?path=/docs/ui-primitives-sheet--docs) [Table](/ui/storybook/?path=/docs/ui-primitives-table--docs) [Tooltip](/ui/storybook/?path=/docs/ui-primitives-tooltip--docs)

**Space things by how closely they belong together, in steps of Tailwind's 4px scale, and lay the screen out for a phone first, then add `md:` for the rest.**

```tsx
import { INBOX_LABEL_COLORS, INBOX_LABELS } from "@orz/fixtures/inbox.ts";
import { Badge } from "@orz/ui/components/badge";
import { Button } from "@orz/ui/components/button";
import { Input } from "@orz/ui/components/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@orz/ui/components/select";
import { SearchIcon, SquarePenIcon } from "lucide-react";

export function MailToolbar() {
  return (
    <div className="flex flex-col gap-2 md:flex-row md:items-center">
      <div className="relative min-w-0 flex-1">
        <SearchIcon className="pointer-events-none absolute top-sunken-centre left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          type="search"
          placeholder="Search, or try is:unread…"
          aria-label="Search mail"
          className="pl-8"
        />
      </div>
      <div className="flex gap-2">
        <Select defaultValue="all">
          <SelectTrigger aria-label="Label" className="flex-1 md:w-36">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All labels</SelectItem>
            {INBOX_LABELS.map((label) => (
              <SelectItem key={label} value={label}>
                <Badge variant="marker" color={INBOX_LABEL_COLORS[label]}>
                  {label}
                </Badge>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button>
          <SquarePenIcon data-icon="inline-start" /> Compose
        </Button>
      </div>
    </div>
  );
}
```

Below 768px the search takes the whole width, and the label filter and **Compose** share the row under it; from `md` up, all three sit on one line. One tree, laid out by CSS.

## Spacing

The more two things belong together, the closer they sit. A handful of steps cover nearly everything:

| Between                                                           | Gap             |       |
| ----------------------------------------------------------------- | --------------- | ----- |
| An icon and its label, inside a control                           | `gap-1.5`       | 6px   |
| Controls that act together: a toolbar, a field and its button     | `gap-2`         | 8px   |
| Modules: between two, and around the region they fill             | `ModuleGrid`    | 8px   |
| The rows of a form, the items of a list with padding of their own | `gap-4`         | 16px  |
| Groups: a form's sections, a card's header and body               | `gap-6`         | 24px  |
| Sections of a page                                                | `gap-8` or more | 32px+ |

Use `gap` on the parent rather than margins on the children: the space then belongs to the layout, and a child dropped in or taken out never leaves a double gap behind. Padding inside a panel matches the gap between its groups, so a card is `p-4` with `gap-4` inside.

```tsx
import { PROFILE, TOKENS } from "@orz/fixtures/account.ts";
import { Button } from "@orz/ui/components/button";
import { GroupHeading } from "@orz/ui/components/group-heading";
import { InfoPopover } from "@orz/ui/components/info-popover";
import { Input } from "@orz/ui/components/input";
import { Label } from "@orz/ui/components/label";
import { List, ListItem } from "@orz/ui/components/list";
import { KeyRoundIcon } from "lucide-react";

export function AccountSections() {
  return (
    <div className="grid gap-8">
      <section aria-labelledby="spacing-profile" className="grid gap-6">
        <GroupHeading asChild>
          <h3 id="spacing-profile">Profile</h3>
        </GroupHeading>
        <div className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="spacing-name">Display name</Label>
            <Input id="spacing-name" defaultValue={PROFILE.name} />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="spacing-email">Email</Label>
            <Input
              id="spacing-email"
              type="email"
              defaultValue={PROFILE.email}
            />
          </div>
        </div>
        <div className="flex justify-end gap-2">
          <Button variant="outline">Discard changes</Button>
          <Button>Save profile</Button>
        </div>
      </section>
      <section aria-labelledby="spacing-tokens" className="grid gap-6">
        <header className="flex items-center gap-1">
          <GroupHeading asChild>
            <h3 id="spacing-tokens">Access tokens</h3>
          </GroupHeading>
          <InfoPopover label="About access tokens">
            Tokens that scripts and bots sign in with.
          </InfoPopover>
        </header>
        <List purpose="collection">
          <ul>
            {TOKENS.map((token) => (
              <ListItem key={token.id} asChild>
                <li className="flex min-h-row items-center gap-2 py-2">
                  <KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
                  <div className="grid min-w-0 flex-1">
                    <span className="truncate font-mono text-ui">
                      {token.name}
                    </span>
                    <span className="truncate text-muted-foreground text-ui-sm">
                      {token.scopes} · {token.lastUsed}
                    </span>
                  </div>
                  <Button
                    variant="destructive"
                    size="sm"
                    aria-label={`Revoke ${token.name}`}
                  >
                    Revoke…
                  </Button>
                </li>
              </ListItem>
            ))}
          </ul>
        </List>
      </section>
    </div>
  );
}
```

**Profile** and **Access tokens** are sections, `gap-8` apart. Inside each, the heading, the body and the buttons are groups, `gap-6`; the form's rows and the tokens are `gap-4`; the two buttons that close the form act together, `gap-2`. The icon in **Compose** above sits `gap-1.5` from its label, which `Button` does by itself.

**Do**

Separate two groups with space first, a line only when space is not enough.

**Don't**

Box every group in its own bordered card, or rule off groups that space already sets apart. Each line competes with the content for attention.

A long run of rows alike, a mailbox or a group of settings, is where space is not enough: each row holds several parts, and a hairline between the rows says which parts go together. A list's rows take it from `List`; a group of settings puts a `Separator` with `purpose="row"` between its rows, which a style whose dialogs part rows by space alone leaves blank.

Groups that are not rows of one list take a `Separator` when space is not enough between them: clusters of buttons in a toolbar, where a gap wide enough to set them apart would scatter the row. It is an element of the layout, so the parent's `gap` spaces it like any other child, and `orientation="vertical"` stands it between the items of a row. A pane's own edge, such as a sidebar's, is that `Pane`'s `edge` instead: the line belongs to the pane and goes with it, and `edge={{ md: "end" }}` draws it only from the breakpoint where the panes stand side by side. Between two ways to do one thing, a `Separator` takes a `label`: the "or" between a sign-in form and the passkey and single sign-on buttons under it.

```tsx
import { Frame } from "@orz/ui/components/frame";
import {
  Toolbar,
  ToolbarButton,
  ToolbarGroup,
  ToolbarSeparator,
} from "@orz/ui/components/toolbar";
import {
  BoldIcon,
  CodeIcon,
  ItalicIcon,
  LinkIcon,
  ListIcon,
  ListOrderedIcon,
  PaperclipIcon,
  QuoteIcon,
} from "lucide-react";
import { Fragment } from "react";

const GROUPS = [
  {
    label: "Text style",
    commands: [
      { label: "Bold", Icon: BoldIcon },
      { label: "Italic", Icon: ItalicIcon },
      { label: "Code", Icon: CodeIcon },
    ],
  },
  {
    label: "Blocks",
    commands: [
      { label: "Bulleted list", Icon: ListIcon },
      { label: "Numbered list", Icon: ListOrderedIcon },
      { label: "Quote", Icon: QuoteIcon },
    ],
  },
];

// The rarest commands come last: where the row does not fit, the toolbar
// moves them into its ⋯ menu first, then a whole group.
const RARE = [
  { label: "Link", Icon: LinkIcon },
  { label: "Attach a file", Icon: PaperclipIcon },
];

export function FormattingToolbar() {
  return (
    <Frame>
      <Toolbar aria-label="Formatting">
        {GROUPS.map(({ label, commands }) => (
          <Fragment key={label}>
            <ToolbarGroup label={label}>
              {commands.map(({ label, Icon }) => (
                <ToolbarButton key={label} aria-label={label}>
                  <Icon />
                </ToolbarButton>
              ))}
            </ToolbarGroup>
            <ToolbarSeparator decorative={false} />
          </Fragment>
        ))}
        {RARE.map(({ label, Icon }) => (
          <ToolbarButton key={label} aria-label={label}>
            <Icon />
          </ToolbarButton>
        ))}
      </Toolbar>
    </Frame>
  );
}
```

The toolbar's buttons fall into three groups: how text looks, how a block is shaped, what is attached. A separator between groups in a `Toolbar` takes `decorative={false}`, so a screen reader hears where one group ends; elsewhere it stays decorative, as it is by default. Where the row does not fit, the toolbar moves the last group into its `⋯` first, and draws no separator beside the `⋯` ([Toolbars](/ui/guidelines/patterns/toolbars/index.md)).

## Modules

**A page of modules lays them out in a `ModuleGrid`, which stands them 8px apart and pads the region by the same amount; the page writes no spacing of its own between modules.** Each `Card` keeps its own rule on every side and a light shadow under it, and the page's ground shows between them.

```tsx
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  ModuleGrid,
} from "@orz/ui/components/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@orz/ui/components/table";

const FIGURES = [
  { label: "Open", value: "38" },
  { label: "Closed this week", value: "112" },
  { label: "Waiting on review", value: "9" },
  { label: "Oldest open", value: "41 days" },
];

const QUEUES = [
  { name: "Inbox", open: 14, oldest: "3 days" },
  { name: "Billing", open: 11, oldest: "41 days" },
  { name: "Releases", open: 8, oldest: "6 days" },
  { name: "Docs", open: 5, oldest: "12 days" },
];

export function ModuleRegion() {
  return (
    <ModuleGrid>
      <ModuleGrid className="grid-cols-2 md:grid-cols-4">
        {FIGURES.map((figure) => (
          <Card key={figure.label} size="sm">
            <CardContent>
              <div className="text-muted-foreground">{figure.label}</div>
              <div className="font-bold text-lg tabular-nums">
                {figure.value}
              </div>
            </CardContent>
          </Card>
        ))}
      </ModuleGrid>
      <ModuleGrid className="lg:grid-cols-[minmax(0,1fr)_16rem]">
        <Card>
          <CardHeader>
            <CardTitle>Queues</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Queue</TableHead>
                  <TableHead className="text-right">Open</TableHead>
                  <TableHead className="text-right">Oldest</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {QUEUES.map((queue) => (
                  <TableRow key={queue.name}>
                    <TableCell>{queue.name}</TableCell>
                    <TableCell className="text-right tabular-nums">
                      {queue.open}
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {queue.oldest}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
        <ModuleGrid>
          <Card>
            <CardHeader>
              <CardTitle>On call</CardTitle>
            </CardHeader>
            <CardContent>alice until Friday, then bob.</CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Next release</CardTitle>
            </CardHeader>
            <CardContent>Thursday, with 6 cards ready.</CardContent>
          </Card>
        </ModuleGrid>
      </ModuleGrid>
    </ModuleGrid>
  );
}
```

Columns and spans go in the grid's `className` (`md:grid-cols-4`, `col-span-full`). An aside of stacked modules is a `ModuleGrid` inside the grid: a grid inside another adds no padding of its own, so the aside's edges line up with its neighbours'. Modules in one row match heights; a stack keeps its modules at their own.

A reader that fills the height beside a rail gives the grid one row, `grid-rows-[minmax(0,1fr)]`, and lets the reader's body (`min-h-0 overflow-y-auto`) and the rail scroll on their own.

Figures that read as one, such as the cells of a single stat strip, are cells ruled off inside one `Card`, never cards set edge to edge.

## Panes and frames

A `Pane` is a region of the app's frame rather than a module: panes meet along their edges, and from `md` up the app draws each one that is read or worked on as a card. A box set among what a surface holds, a block of code, a file, a set of tabs that is one block among others, is a `Frame`, its heading line on its lid and its closing actions on its foot, both toolbars that give way as the frame narrows. Tabs that switch everything a pane shows are no box in it: `Tabs variant="pane"` runs their strip across the pane under its header, and the current panel fills the rest of the pane and scrolls on its own, padded as the pane's content is. A table that fills a pane, as the tasks beside the open one's details do in the [Tasks demo](/ui/demos/tasks/index.md), takes `fill`: it takes the rest of the pane's height and scrolls inside it, its header staying at the top, while the pane's toolbars stay put. What stands on the ground and what goes inside what, cards, panes, frames and the links between them, is on [Surfaces](/ui/guidelines/foundations/surfaces/index.md). The pull request demo's comments, its checks and its reply box are cards on the ground; every block of code in a document is a frame ([Long content](/ui/guidelines/patterns/long-content/index.md)).

## Breakpoints

Tailwind's breakpoints are the library's, and the line that matters is `md`, 768px: below it is a phone, at or above it is everything else.

| Prefix       | From           | Use                                                                                                        |
| ------------ | -------------- | ---------------------------------------------------------------------------------------------------------- |
| —            | 0              | The phone layout: one column, full-width fields, navigation in a `Sheet` or a `TabNav` on a row of its own |
| `sm:`        | 640px          | Small adjustments: a dialog's buttons side by side                                                         |
| `md:`        | 768px          | The desktop layout: side-by-side panes, a sidebar, a toolbar on one line                                   |
| `lg:`, `xl:` | 1024px, 1280px | Extra panes that only fit on a wide screen, such as a contents column                                      |

A layout change is CSS (`md:flex-row`) wherever the same elements can be rearranged. Branch in JavaScript only when the tree itself differs, such as a pane that becomes a pushed page, and then use the library's own query so CSS and script never disagree on where the line is:

```tsx
import { MD_UP, useMediaQuery } from "@orz/ui/hooks/use-media-query";

const wide = useMediaQuery(MD_UP);
```

```tsx
import { INBOX_PEOPLE, INBOX_THREADS } from "@orz/fixtures/inbox.ts";
import { Frame } from "@orz/ui/components/frame";
import { List, ListItem } from "@orz/ui/components/list";
import {
  NavList,
  NavListFrame,
  NavListItem,
  NavListLink,
} from "@orz/ui/components/nav-list";
import { Pane } from "@orz/ui/components/pane";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetTitle,
} from "@orz/ui/components/sheet";
import { ToolbarButton } from "@orz/ui/components/toolbar";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@orz/ui/components/tooltip";
import { cn } from "@orz/ui/lib/utils";
import { Markdown } from "@orz/ui-markdown";
import {
  ArchiveIcon,
  ArrowLeftIcon,
  FileTextIcon,
  InboxIcon,
  PanelLeftIcon,
  SendIcon,
  StarIcon,
  Trash2Icon,
} from "lucide-react";
import { useState } from "react";

const PLACES = [
  { title: "Inbox", Icon: InboxIcon },
  { title: "Starred", Icon: StarIcon },
  { title: "Sent", Icon: SendIcon },
  { title: "Drafts", Icon: FileTextIcon },
  { title: "Archive", Icon: ArchiveIcon },
  { title: "Trash", Icon: Trash2Icon },
];

const THREADS = INBOX_THREADS.filter((thread) => !thread.folder).slice(0, 5);

function Folders() {
  return (
    <NavListFrame asChild>
      <nav aria-label="Folders" className="h-full">
        <NavList>
          {PLACES.map(({ title, Icon }) => (
            <NavListItem key={title}>
              <NavListLink current={title === "Inbox"} asChild>
                <button type="button">
                  <Icon />
                  {title}
                </button>
              </NavListLink>
            </NavListItem>
          ))}
        </NavList>
      </nav>
    </NavListFrame>
  );
}

export function MailPanes() {
  const [open, setOpen] = useState<string | null>(null);
  const [folders, setFolders] = useState(false);
  const thread = THREADS.find(({ id }) => id === open);
  return (
    <TooltipProvider>
      <Frame asChild>
        <Pane purpose="app" className="flex h-96">
          <Pane
            purpose="sidebar"
            edge="end"
            className="w-40 shrink-0 p-2 max-lg:hidden"
          >
            <Folders />
          </Pane>
          <Pane
            purpose="panel"
            edge={{ md: "end" }}
            asChild
            className={cn(
              "flex min-w-0 flex-1 flex-col md:w-56 md:flex-none",
              thread && "max-md:hidden",
            )}
          >
            <section aria-label="Conversations">
              <Pane
                purpose="toolbar"
                edge="bottom"
                className="flex shrink-0 items-center gap-1 px-2 py-1.5"
              >
                <Tooltip>
                  <TooltipTrigger asChild>
                    <ToolbarButton
                      size="icon-sm"
                      aria-label="Folders"
                      className="lg:hidden"
                      onClick={() => setFolders(true)}
                    >
                      <PanelLeftIcon />
                    </ToolbarButton>
                  </TooltipTrigger>
                  <TooltipContent>Folders</TooltipContent>
                </Tooltip>
                <span className="px-1 font-medium text-ui">Inbox</span>
              </Pane>
              <List purpose="listbox" className="flex min-h-0 flex-1 flex-col">
                <ul className="min-h-0 flex-1 overflow-y-auto py-1">
                  {THREADS.map((each) => (
                    <li key={each.id}>
                      <ListItem current={each.id === open} asChild>
                        <button
                          type="button"
                          aria-current={each.id === open ? "true" : undefined}
                          onClick={() => setOpen(each.id)}
                          className="grid w-full px-3 py-2 text-left"
                        >
                          <span className="truncate text-muted-foreground text-ui-sm">
                            {INBOX_PEOPLE[each.messages[0]?.from ?? ""]}
                          </span>
                          <span className="truncate text-ui">
                            {each.subject}
                          </span>
                        </button>
                      </ListItem>
                    </li>
                  ))}
                </ul>
              </List>
            </section>
          </Pane>
          <Pane
            purpose="panel"
            asChild
            className={cn(
              "min-w-0 flex-1 flex-col",
              thread ? "flex" : "max-md:hidden md:flex",
            )}
          >
            <article aria-label="Conversation">
              {thread ? (
                <>
                  <Pane
                    purpose="toolbar"
                    edge="bottom"
                    className="flex shrink-0 items-center gap-1 px-2 py-1.5"
                  >
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <ToolbarButton
                          size="icon-sm"
                          aria-label="Back to inbox"
                          className="md:hidden"
                          onClick={() => setOpen(null)}
                        >
                          <ArrowLeftIcon />
                        </ToolbarButton>
                      </TooltipTrigger>
                      <TooltipContent>Back to inbox</TooltipContent>
                    </Tooltip>
                    <h3 className="truncate px-1 font-medium text-ui">
                      {thread.subject}
                    </h3>
                  </Pane>
                  <Pane
                    purpose="document"
                    className="flex min-h-0 flex-1 flex-col"
                  >
                    <Markdown className="min-h-0 flex-1 overflow-y-auto p-4 text-ui">
                      {thread.messages[0]?.body ?? ""}
                    </Markdown>
                  </Pane>
                </>
              ) : (
                <Pane
                  purpose="document"
                  className="grid flex-1 place-content-center p-4"
                >
                  <p className="text-muted-foreground text-ui">
                    Pick a conversation to read it.
                  </p>
                </Pane>
              )}
            </article>
          </Pane>
          <Sheet open={folders} onOpenChange={setFolders}>
            <SheetContent side="left" className="w-64 p-2 pt-12">
              <SheetTitle className="sr-only">Folders</SheetTitle>
              <SheetDescription className="sr-only">
                Mail's folders
              </SheetDescription>
              <Folders />
            </SheetContent>
          </Sheet>
        </Pane>
      </Frame>
    </TooltipProvider>
  );
}
```

Narrow the window to walk the table. From `lg` up the folders sit in a pane of their own; below it they move into a `Sheet` behind **Folders**. From `md` up the conversation opens beside the list; below it, it replaces the list and the arrow goes back. Every change is a `max-md:` or `lg:` class, so the tree stays the same. A dialog's footer puts its buttons side by side from `sm` up by itself; [Overlays](/ui/guidelines/patterns/overlays/index.md) shows one.

**Width decides the layout; the pointer decides the room around the controls.** A tablet is wide and touched, a narrow desktop window is small and clicked. Do not size controls by width, and do not lay out by pointer: the components already make room on a coarse pointer by themselves.

## Width

- Content reflows down to 320px wide with no sideways scrolling ([WCAG 1.4.10](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html)); only something two-dimensional by nature, a table, a log, a diff, scrolls inside its own box.
- A row that holds a long label gives that label `min-w-0 flex-1` and `truncate`, so the label shrinks and its neighbours keep their size.
- The window's frame meets its edges: the header, a sidebar and a toolbar run to the window's sides, and a tool's panes fill the window. A filled pane never sits inside a centred box, where its fill would stop short of the edge and float.
- Prose stops at a readable measure (`max-w-prose`, `max-w-3xl`) and centres in the window. A sidebar pushes it aside only when the window is too narrow to centre it clear of the sidebar. A page's contents sit right against the text.
- Pages that read alike keep the text in one place: a page without a sidebar leaves the sidebar's room free all the same, so its text starts where a page with one starts.

## Corners

`--radius` is the theme's corner, 2px by default, and the `rounded-*` steps scale from it: `rounded-lg` is `--radius` itself, `rounded-md` and `rounded-sm` are smaller, `rounded-xl` and up are larger. Use the steps rather than pixel values, so a theme that squares its corners squares yours too. A box inside a rounded box takes a smaller step than its parent, so the two curves stay concentric. The components round to `--radius` too: a card and a dialog, a menu or a popover, a viewer's frame, a control and a chip; a row, a tab and a block inside a part stay square.

## On each platform

- **Pointer.** Panes sit side by side and the page pads `px-10` or so at the edges.
- **Touch.** A phone pads `px-4` to `px-5`, enough to keep content off the screen's edge and off the system's back gesture. Keep content out of the notch and the home indicator with the safe-area insets; [Touch & mobile](/ui/guidelines/platforms/touch-and-mobile/index.md#safe-areas) covers them.

## In the demos

- [Mail](/ui/demos/mail/index.md): Narrow the window. The sidebar folds to a rail below xl, and below md one pane shows at a time, with the folders in a Sheet.
- [Notes](/ui/demos/notes/index.md): Below lg there is room for the editor or the preview, not both. Below md the list and the note take turns.
- [Pull request](/ui/demos/pull-request/index.md): Below lg the details column drops under the conversation. On a phone the jobs become a row above the log, and the pull request's pages that do not fit wait in a ⋯, as the repository's sections do.
