# Layout Guide — Agent Instructions

This file is the single source of truth for spacing, grid systems, responsive design, and layout rules in this design system.

## Compose from the task

For a new or substantially recomposed view, establish a short internal composition brief before choosing its geometry:

- **Task and focal content:** What must the user understand or do first? Identify the content or action that deserves priority, based on the user's task and source material.
- **Reading and interaction order:** What context must precede that focal content, and what detail can follow or be disclosed on demand?
- **Grouping and density:** Which items need simultaneous comparison, which belong together, and which require sustained reading?
- **Available room:** What must remain understandable and actionable as the viewport narrows or content grows?

Use those answers to choose a composition. Preserve existing package component anatomy, states, and dimensions; vary the arrangement around those components. Use the routed component guide to select controls and inspect the installed package for exact APIs.

### Example composition briefs

These illustrate reasoning, not mandatory page templates. Use them only when the task matches; adapt the arrangement to actual content and available space.

| Task | Example brief | Why this composition fits |
| --- | --- | --- |
| Compare a collection of records | Put shared attributes in aligned columns with nearby filters. Keep descriptive metadata secondary and encode actual statuses consistently. Offer object details through the existing contextual inspection pattern. | Shared columns support comparison; keeping details subordinate preserves the collection context. |
| Edit one object's settings | Group fields by the decisions they support, with persistent labels and help beside the relevant control. Establish a clear reading order and place the commit action with the workflow it completes. | Proximity explains relationships; a focused form avoids making the user search across unrelated sections. |
| Read a conversation with supporting material | Give messages a continuous reading flow. Place source material where it can be consulted without losing the relevant message; stack it in reading order when side-by-side space is insufficient. | Sustained reading and cross-reference determine the geometry, rather than a fixed dashboard grid. |

Do not manufacture a winning row, headline metric, status, or decorative feature merely to create a focal point. When peers have equal importance, give the group a clear heading and preserve equal treatment within it. Scientific reports use their separately routed summary layout and chart evidence.

For data tables, select the concise value needed for comparison in each column. Cells default to one hierarchy level, without stacked captions or metadata. Keep values on one line without wrapping. Tables fill the available width: start with capped content-sized columns, distribute spare space proportionally across data columns when they fit, and otherwise retain their preferred widths with horizontal scrolling. Selection and action columns stay compact. Overlong cells also scroll horizontally. Use the [table rules](components/selection.md#tables) to handle supporting detail and exceptional task needs.

Scrolling content clips at a visible boundary: a browser viewport edge, a drawn border, or a contextual divider that appears while content passes behind a fixed surface. Do not create an unmarked clipping edge inside padding. Place padding inside the moving content and let the scroll hitbox reach the enclosing boundaries. Resting content still follows the shared alignment insets. In tables, retain visible separators on pinned columns as adjacent columns move behind them.

### Learning from a visual reference

When a task includes an external style document or screenshot, identify the useful relationship: hierarchy, alignment, pacing, grouping, or the balance between content and surrounding UI. Translate that relationship into Fractal's existing tokens and components. A marketing page's large section gaps or oversized headline are observations about that page, not automatic defaults for a product workspace. Apply explicit user-requested departures through the evidence contract's precedence rules.

Describe the intended visual effect in concrete terms. For example, “keep the filters compact and give the results the largest uninterrupted region” supplies a usable composition decision; “make it premium” leaves the decision unresolved.

---

## Spacing: The 8pt Grid

All spacing values use the 4px grid. Prefer 8px increments for layout and 4px increments for compact component relationships. An off-grid value is allowed only when the user explicitly requests it; treat it as a temporary stopgap and leave a `TODO` naming the value and intended token-based repair.

All tokens live in `layout.css` as `--space-0` through `--space-13`.

### The Most Important Rule

Internal spacing (inside a component) must be LESS than or equal to external spacing (between components). When this is violated, elements feel disconnected from their containers.

### Proximity Creates Meaning

| Relationship | Spacing | Tokens |
|---|---|---|
| Related items | 8–16px | `--space-2` to `--space-4` |
| Loosely related | 24–32px | `--space-6` to `--space-7` |
| Different sections | 48–64px | `--space-9` to `--space-10` |
| Different content areas | 64–128px | `--space-10` to `--space-13` |

### Common Usage

| Context | Token | Value |
|---|---|---|
| Icon gaps, tight inline | `--space-1` | 4px |
| Related elements (icon + label) | `--space-2` | 8px |
| Label-to-input gap | `--space-2` | 8px |
| Default content-container padding | `--space-4` | 16px |
| Generous content-container padding, form field gaps | `--space-6` | 24px |
| Section spacing | `--space-7` | 32px |
| Page section spacing | `--space-10` | 64px |

---

## Shared control metrics

Matching buttons, dropdowns, and single-line inputs use shared control metrics. The resulting block size is derived from typography, padding, and two 1px borders, rather than an independent fixed height. Inline padding is identical across these component categories at a given size. See the component guide for alignment and label rules.

| Size | Text / line box at 16px root | Block padding | Inline padding | Intended use |
| --- | --- | --- | --- | --- |
| sm | 12px / 20px | 4px | 12px | Compact toolbars |
| md | 14px / 20px | 8px | 12px | Compact forms and filters |
| lg | 14px / 20px | 12px | 16px | Default forms and filters |
| xl | 14px / 20px | 16px | 20px | Large touch targets |

Use `lg` by default for controls. The supported scale is `sm`, `md`, `lg`, and `xl`; use smaller sizes only for intentionally compact layouts. `xs` is not supported.

The corresponding `--control-{size}-*` tokens store font size and line box in rem, and padding as spacing-token aliases. `--control-label-gap` and `--control-icon-gap` use 8px. Icon slots are 16px for sm and 20px for md/lg/xl, capped by the line box. These are shared metrics, not separate component height tokens. Border thickness adds 2px to the content-plus-padding box; it does not require off-grid padding to compensate.

## Grid Systems

- Use a **12-column grid** (divides evenly by 2, 3, 4, 6)
- Gutter width: 16–32px (must use spacing tokens: `--space-4` to `--space-7`)
- Container max-widths by purpose:
  - 640px — narrow (reading, forms)
  - 768px — reading column
  - 1024px — app layout
  - 1280px — wide app
  - 1536px — dashboard

---

## Alignment

- **Left-align text** (centered text is harder to scan)
- Align elements to a shared left edge wherever possible
- Optical alignment sometimes matters more than mathematical alignment (e.g., play button triangles need visual centering, not exact centering)

### Application navigation header alignment

Adjacent application-shell headers share one top edge and one bottom divider position. Use `--shell-header-height` from `layout.css` for the sidebar brand/account row and the main navigation or breadcrumb row. The default is 3.5rem (56px at the default root), including the 1px divider. There is no per-header size scale: choosing independent sizes recreates the alignment failure.

Use border-box sizing, a shared block size, no flex shrink, and vertically centered single-row content. Padding must fit inside that size rather than increasing it. Place page titles, descriptions, tabs, and multi-row toolbars below the navigation row; they are content, not shell chrome. This narrow navigation row is an intentional exception to equal padding on major content containers.

Use Fractal UI's shared shell-header styling alongside `SidebarHeader`; inspect the package for exact usage. If accessibility or a product constraint requires more room, adjust the token once on the common shell ancestor so all adjoining headers change together. Preserve accessible controls and text; do not clip them to enforce alignment. At responsive breakpoints, collapse or reflow navigation coherently rather than letting one header wrap and grow independently. Headers that occupy separate rows or overlay layers need not share this baseline.

**Forbidden outcome:** a stepped horizontal divider between adjoining navigation regions caused by independent height, padding, border-box, or flex sizing.

### Container spacing and shared content edges

These rules apply to major content containers such as page sections, substantial content cards, and panel shells. They govern composition around components; compact controls and table cells retain their own internal sizing rules.

**Shared content edges — required invariant.** Establish a consistent inline inset for each container. Align its heading, toolbar boundary, body content, first table column, and footer to that content edge; align corresponding trailing content to the opposite edge. Align the intended anchors: an input's outer boundary can align with the section heading while its text retains the input's internal padding and icon slot. Do not remove valid component padding to align every nested text node.

Table backgrounds and dividers may extend to the container boundary. In that arrangement, the first and last header/body cells use the container's outer inline inset. Interior column spacing and compact row block padding remain independent. Measure the total inset from the container boundary: do not add a full container inset around a table and then accidentally add its cell padding again. When a leading selection or icon column is needed, treat it as an intentional column with a consistent slot rather than moving individual rows.

**Peer padding — required invariant.** Containers presented as peers in the same page layer share a padding treatment. Choose one spacing token for the peer group according to its density; apply the same choice when that group changes at a responsive breakpoint. A persistent details pane alongside a collection follows this rule when both are presented at the same hierarchy level. An overlay inspector or modal is a separate interaction layer and may follow its own padding treatment. A component name or different background alone does not justify a different inset.

**Equal outer padding — default.** Use the same spacing token for block and inline padding on major content containers. Choose the default or generous container inset for the group rather than assigning 16px to a section and 24px to its peer merely because the latter is called a card. This describes the shell's outer content clearance, not repeated padding on every nested subsection.

Allowed exceptions need a concrete content or interaction reason, such as full-width table rows, a scrolling body, or a fixed action footer. Record the reason briefly with the composition decision or relevant implementation. Preserve shared inline content edges through header, body, and footer even when their block spacing differs. Component defaults or arbitrary visual variety are not sufficient reasons for an exception.

For implementation, express the shared inset once using an existing spacing token and reuse it through supported component composition points. Grid or flex layout may arrange the regions, but does not replace their shared inset. Do not rebuild a package component to adjust its container alignment; inspect its supported styling API and make a reusable package extension only if recurring compositions require it.

**Forbidden outcomes:** unexplained inset changes between peer containers; a table's first content column drifting from its containing section's content edge; double-counted wrapper and cell insets; asymmetric major-container padding without a content or interaction reason.

---

## Whitespace

- Whitespace creates grouping, hierarchy, and breathing room
- More whitespace around an element = more importance
- Prefer whitespace over visible dividers to separate sections
- If dividers are needed, make them subtle (1px, low opacity)

### Divider structure

**A standalone, bordered content region has a complete outer boundary.** Open-ended horizontal borders are appropriate for bands that genuinely span their parent region, rather than floating inside its padding.

Use at most two divider treatments within a container. A **structural divider** separates primary regions and spans their full shared boundary, meeting enclosing borders or another structural divider. An **inset divider** separates subordinate groups within a primary region and spans that region's content edges. Both use the same 1px, surface-aware subtle border treatment; do not create additional hierarchy with thicker or darker lines, or progressively shorter insets. Express further grouping with spacing and typography.

Default to structural dividers when separation is needed. Determine the regions from their task and content before drawing boundaries. Padding belongs inside each region, so structural lines reach the shell while text retains consistent insets. Primary sections in a details container may be metadata, annotations, and review; separators between them reach both side borders. A heading and its own content do not automatically constitute separate regions.

#### Divider conditions

Keep layout conditions together in this table. Component-specific interaction conditions remain in their owning guide and are linked here; do not create an unrelated global list of exceptions.

| If… | Then… |
| --- | --- |
| A standalone content region uses borders to establish its container | Draw a complete outer boundary. Top and bottom borders alone are appropriate only for a band that genuinely spans its parent region; do not leave their endpoints floating inside parent padding. |
| Primary regions are stacked vertically | Use full-width separators between regions, reaching the enclosing side borders. |
| Primary regions sit side by side | Use full-height separators across their shared region, from its top boundary to its bottom boundary. |
| A shared heading spans a body that is divided into primary regions | Add a full-width boundary beneath the heading. The body's internal structural dividers meet this boundary and the enclosing bottom/side border; they do not stop in header padding. |
| A heading introduces one continuous body | Do not automatically add a divider below the heading. Use spacing unless the task or interaction establishes a distinct boundary. |
| A primary region needs a second level of internal grouping | An inset divider may run between that region's content edges. Do not use an inset line merely because the parent has padding. |
| The only reason to add a line is to give another line an endpoint | Reconsider whether those primary regions need a structural split. A new boundary must describe real grouping; avoid decorative grids. A shared heading over a genuinely subdivided body meets the preceding condition. |
| Content scrolls behind a fixed header or footer | Follow the owning component's scroll-aware boundary rules, such as [SidePanel](components/side-panel.md). A conditional full-span divider is a state of the structural treatment, not a third hierarchy level. |
| A responsive layout stacks previously side-by-side regions | Change the separator's orientation to follow the new shared boundary. Remove obsolete vertical segments and preserve the section insets. |

These rules concern container partitions. Chart axes, gridlines, data marks, and table cell grids retain their domain-specific roles; do not extend chart gridlines to card borders or count data-bearing strokes as divider hierarchy.

**Forbidden outcomes:** primary separators ending in arbitrary padding; an incomplete structural divider floating between regions; inset dividers used for every level; a header divider added to every card regardless of content; padding removed so content touches a new boundary.

---

## Responsive Design

### Breakpoints

All breakpoint tokens live in `layout.css`:

| Token | Value | Context |
|---|---|---|
| `--bp-sm` | 640px | Mobile landscape |
| `--bp-md` | 768px | Tablet portrait |
| `--bp-lg` | 1024px | Tablet landscape / small desktop |
| `--bp-xl` | 1280px | Desktop |
| `--bp-2xl` | 1536px | Large desktop |

### Design mobile-first, then add complexity for larger screens.

Responsive means the experience is GOOD at every size, not just that it fits.

- **Mobile:** Single column, bottom nav, full-width buttons, no hover states
- **Tablet:** Two columns where appropriate, adaptive density
- **Desktop:** Multi-column, sidebar nav, hover states, higher information density

### Mobile-First Component Adjustments

| Component | Mobile | Tablet | Desktop |
|---|---|---|---|
| Nav | Bottom tabs or hamburger | Top nav, simplified | Full top nav + sidebar |
| Buttons | Full width; use shared size meeting touch-target minimum | Auto width; shared size by density | Auto width; shared size by density |
| Cards | Single column, full width | 2 columns | 3–4 columns |
| Tables | Capped columns; horizontal cell/table scroll | Content-sized columns with scroll | Content-sized columns with scroll when needed |
| Modals | Use the package's mobile treatment | Use the package's centered treatment | Select the package variant by content and workflow |
| Forms | Single column, large targets | Single or two column | Two column for long forms |
| Typography | Base 16px | Base 16px | Base 16px (scale up headings) |

### Touch Target Rules

- Minimum: 44×44px (Apple HIG) / 48×48dp (Material)
- Comfortable: 48×48px
- Space between targets: at least 8px (`--space-2`)
- Bottom of screen = easiest thumb reach
- Top corners = hardest thumb reach

### Viewport Tricks

```css
/* Proper mobile viewport height (accounts for browser chrome) */
.full-height { height: 100dvh; }

/* Safe area for notched phones */
.container {
  padding-left: env(safe-area-inset-left);
  padding-right: env(safe-area-inset-right);
  padding-bottom: env(safe-area-inset-bottom);
}
```
