UI Engineering Invariants
Apply these rules only when the corresponding component or pattern is already present in the UI being built or modified. Every rule is a measurable geometric, ergonomic, or contrast invariant that adapts to the project's existing design tokens.
CSS Baseline & Styling Stacks:
- Rules assume Baseline 2023+ browser support (
lh,cap,pi,subgrid,scroll-padding-*,scroll-margin-*,overscroll-behavior,scrollbar-gutter, logical properties). For older targets, gate optical math on all three primitives together—@supports (padding: calc(1lh + 1cap * pi))(never1capalone; Firefox shippedcapseveral releases beforelhin v120)—and fall back to numeric equivalents derived from existing font size, line-height, and0.2146(1 - π/4). - In utility-first codebases (Tailwind, UnoCSS), bind local custom properties
(
--py,--bw,--r,--icon-size) directly from the existing utility scale rather than refactoring away from utility classes. - Bind every referenced token before use. An undefined custom property
makes the whole declaration invalid at computed-value time, so the property
silently falls back to its initial value (e.g.,
border-radiusresets to0and a pill renders square). Map--py,--bw,--icon-size, etc. to the project's existing values, or give eachvar()a fallback (var(--py, 0px)).
Taste-Preservation Guardrails
- Never prescribe visual taste. Do not dictate or alter colors, font families, font weights, border styles, shadows, corner-radius sizes, density, or visual themes.
- Never suggest adding or replacing UI patterns. Do not recommend switching to or introducing pill buttons, tabs, hover cards, indicator bars, or other components unless the design already uses them.
- Keep every rule conditional. Apply a rule only when its trigger condition
matches the component under construction, and compute values from whatever
tokens (
--py,--r,--icon-size,lh,cap, surface colors) already exist. - Use measurable criteria only. Rely on CSS math, pointer/keyboard state machines, layout geometry, and WCAG contrast ratios. Never justify changes with subjective descriptors ("clean", "soft", "modern", "sleek", "minimal").
Cross-Cutting Invariant: Theme-Adaptive Contrast
Verify across every theme the project supports (light, dark, high-contrast):
- Normal text: ≥
4.5:1contrast against its background. - Large text (≥
24pxregular or ≥18.67pxbold): ≥3:1. - Interactive non-text UI (control boundaries required to identify hit
areas, focus rings, meaningful icons, active indicators): ≥
3:1against adjacent surfaces. - WCAG exemptions (do not override intentional styling): Disabled (non-operable) controls, purely decorative borders or dividers not needed to identify an interactive boundary or state, and logotypes are exempt. WCAG's "inactive" means disabled, not unselected: unselected tabs, nav items, and toggles are still operable and must meet contrast.
Trigger-Based Rules
1. Pill Buttons — Optical End Padding
When building a single-line full-radius pill control containing text or a circular icon:
- Do not rely on
border-radius: 999pxwith symmetric horizontal padding. - Compute the pill radius from vertical padding (
--py), half line-height (0.5lh), border width (--bw), and any enforced--min-h(or fixed--h, where--pill: calc(var(--h) / 2)), then derive text-edge arc compensation (--edge):.pill { --bw: 0px; /* set to border-width when bordered */ --min-h: 0px; /* set to min-height or fixed height when constrained */ --pill: max(var(--py) + 0.5lh + var(--bw), var(--min-h) / 2); --r: var(--pill); --edge: calc(var(--r) * (1 - pi / 4)); border-radius: var(--r); } - Add
var(--edge)to inline padding on text-adjacent edges. Keep circular icons concentric with the outer arc (r_inner = max(0px, var(--r) - inset)). - Sub-pill generalization: If scaling
--edgedown for rounded rectangles (--r < var(--pill)), multiply by the unitless ratior / pillusing unitless tokens (dividing two<length>values insidecalc()requires CSS Values 4 typed arithmetic, which has narrower browser support thanlh,cap, andpi).
2. Buttons & Inline Icons — Half-Leading Compensation
When building a button or inline control with text and optional icons:
- Do not use arbitrary symmetric padding that ignores
line-heighthalf-leading, and do not resize existing icon-grid tokens (16px,20px, etc.) to1lhunconditionally. - Scope of change: This rule intentionally replaces the control's existing horizontal padding with a value derived from its existing
--pyand line-height. Keep--pyand the project's spacing scale unchanged; onlypadding-inlineis re-derived. - Derive horizontal padding from
--pyplus vertical half-leading, bind--icon-sizeto the design system's existing icon size (defaulting to1lh), and pull only outer-edge icons inward via:first-child/:last-childso outer horizontal clearance matches vertical clearance without collapsing the icon-to-label gap:.btn { --px: calc(var(--py) + (1lh - 1cap) / 2); --icon-size: 1lh; /* override with existing pixel-grid icon size if fixed */ --icon-pull: calc(var(--py) - var(--px) + max(0px, (1lh - var(--icon-size)) / 2)); padding-block: var(--py); padding-inline: var(--px); } .btn > .icon { width: var(--icon-size); height: var(--icon-size); } .btn > .icon:first-child { margin-inline-start: var(--icon-pull); } .btn > .icon:last-child { margin-inline-end: var(--icon-pull); } - Icon-only vs. icon+text: On an icon-only button (a single
.iconchild and no text), matching both:first-childand:last-childis intentional—it equalizes both inline edges to match the vertical clearance. When pairing an icon with text, wrap the label in an element (e.g.,<span>) or use explicit.icon-start/.icon-endclasses, because bare text nodes are invisible to:first-child/:last-childand would cause a leading/trailing icon to match both selectors and collapse the inner gap. - Script note:
(1lh - 1cap) / 2calibrates for Latin/alphabetic cap-height; for CJK-primary labels where glyphs fill nearly1ic, use(1lh - 1ic) / 2(or keep existing script-tuned padding tokens). - Composing Rule 1 + Rule 2 (
.btn.pill): Setpadding-inline: calc(var(--px) + var(--edge))so text edges get both half-leading and arc compensation. On an outer-edge circular icon (e.g., avatar or round badge), pull inward bycalc(var(--pill) - var(--bw) - var(--icon-size) / 2 - var(--px) - var(--edge))so it sits concentric with the pill arc in both intrinsic and fixed-height pills (which simplifies tovar(--py) - var(--px) - var(--edge)when intrinsic height wins and--icon-sizeis1lh). On an outer-edge non-circular icon, keep--icon-pullso it retains--edgearc clearance.
3. Icons Next to Wrapping Text & Card Headings
When placing an icon beside text that can wrap to multiple lines (alerts, list items, card headers, multi-line buttons, controls with descriptions):
- Never use
align-items: centeron the flex row. - Use
align-items: start, anchor the icon to the first line withmargin-top, and balance container padding/gap with--px: calc(var(--py) + (1lh - 1cap) / 2). - Match the first line's
lhcontext:1lhresolves against the icon's own computedline-height, not a sibling heading's. When an icon sits beside a heading (e.g.,<h3>) whosefont-sizeorline-heightdiffers from the flex container, inherit or share the heading's line-height token (--first-line-lh) on the icon before computingmargin-top: calc((var(--first-line-lh, 1lh) - var(--icon-size)) / 2)(or0when--icon-sizeequals--first-line-lh). --first-line-lhmust be a<length>. If the project stores line-height as a unitless multiplier (e.g.,1.25), convert it first (--first-line-lh: calc(1.25 * 1.5rem), using the heading's multiplier and font size); a unitless value makes thecalc()invalid.
4. Destructive Actions — Close & Delete Controls
When building closable tabs, dismissible chips, or items with inline destructive buttons (such as ×):
- Never hide destructive actions behind
:hover. Keep them persistently visible and keyboard-focusable. - Enforce a minimum hit target on the destructive control: ≥
24px × 24pxCSS pixels on fine pointers (WCAG 2.5.8 Target Size Minimum, AA) and ≥44px × 44pxon coarse pointers (WCAG 2.5.5 Target Size Enhanced, AAA; adopted here as the coarse-pointer target). - Non-overlap on coarse pointers: When expanding a destructive hit area beyond its visual glyph (e.g., via padding or
::after), verify WCAG 2.5.8 target spacing—the expanded hit box must never overlap adjacent controls or swallow the parent chip/tab's selection target. Increase inter-item spacing or container size rather than letting hit targets collide. - Give closable tabs a minimum width so the non-destructive selection area reliably outweighs the destructive close target. Default to
min-width: 8emunless the project already sets a tab minimum width. - Reserve hover/focus-within reveal strictly for non-destructive secondary menu triggers (such as
⋮), and keep them visible under@media (hover: none)so touch users can reach them.
5. Collapsible Sidebar Button Toggles
When building a collapsible sidebar or drawer controlled by a header- or rail-anchored toggle button (not a border-mounted split-pane drag/collapse handle on the divider edge):
- Never place the button where expanding or collapsing shifts its horizontal position.
- Anchor it in a fixed horizontal slot (constant
inset-inline-startoffset in both states) so consecutive clicks never require moving the pointer.
6. Hover Cards & Interactive Popovers
When building pointer-triggered hover cards, interactive tooltips, or flyout submenus:
- Do not rely solely on a close delay timer or a single-origin safe triangle.
- Use a safe-pentagon pointer corridor covering the trigger rect and the two diagonal tangents connecting the trigger/pointer to the card's near corners: keep the card open inside the union of trigger, card, and corridor, and close immediately on exit so diagonal travel never flickers and lateral travel to adjacent triggers is never blocked.
- Prefer existing primitives: If the project already uses a positioning/overlay library with safe-polygon support (e.g., Floating UI
safePolygon, Radix submenu pointer grace areas, Ariakit), use it instead of hand-rolling polygon geometry across placements, scroll containers, and zoom levels. RadixHoverCarduses open/close delays, not a polygon, so it does not satisfy this rule on its own. - WCAG 1.4.13 parity: Ensure the card is hoverable, keyboard-focus accessible, persistent until dismissed/unhovered/unfocused, and dismissible via
Escapewithout moving pointer or focus.
7. Scrollable Tab Bars
When building a horizontally scrollable tab strip:
- Hide native scrollbars (
scrollbar-width: none/::-webkit-scrollbar { display: none }) without removing scroll affordances:- Render CSS edge fades (
mask-image) on any side with remaining overflow across all pointer types (covers touchscreens, hybrid laptops, and trackpad horizontal gestures). - Additionally layer
</>scroll chevrons only on sides with hidden tabs under@media (hover: hover) and (pointer: fine).
- Render CSS edge fades (
- Boundary click-through lock: When a click reaches the start or end scroll boundary while the pointer is still hovering the chevron, keep that chevron mounted and
disableduntilpointerleavebefore hiding it—never unmount it directly under an active pointer. - Keyboard focus clearance: Set
scroll-padding-inlineon the scroll container to at least the width of the fade or chevron overlay so keyboard-focused tabs scroll clear of overlays. - Concentric nested radii: When tabs sit inside a rounded track, satisfy
r_inner = max(0px, r_outer - inset)using the container's existing radius and padding tokens.
8. Active Navigation Indicators
When indicating the active item in a navigation bar, sidebar, or tab list:
- Do not rely solely on low-contrast background tints or font-weight shifts; include a non-color or ≥
3:1contrast structural cue. - Prevent scrollbar collision and bezel clipping: When using a vertical indicator bar, never let it collide with or sit occluded beneath a scrollable container's scrollbar (reserve trailing clearance beyond the scrollbar gutter), and never let it clip against rounded display bezels, notches, or OS window corners (respect
env(safe-area-inset-*)and corner inset clearance). Flush rail-edge indicators remain valid on unobstructed flat chrome.
9. Timelines & Connector Rails
When building a vertical timeline or stepper with rails connecting circular node markers:
- Maintain equal, measurable top and bottom optical gaps where vertical rail segments meet each circular marker (
top-gap === bottom-gap, zero stroke-to-circle collisions). - Implement via an explicit flex/grid marker column where upper and lower rail segments are separated from the circle by
row-gap: var(--rail-gap), or via a continuous rail masked behind the circle with a uniform cutout (mask-imageor ring offset).
10. Multi-Row Forms — Scoped Subgrid
When building horizontally aligned label-control forms across sibling rows or nested fieldsets:
- Use
grid-template-columns: subgridscoped to viewports where labels and controls sit side by side (do not force subgrid onto stacked narrow-viewport layouts). Each row or fieldset must itself be a grid item spanning the parent's tracks (display: grid; grid-column: 1 / -1), orsubgridhas no tracks to inherit. - Bound the label track (e.g.,
minmax(auto, 24ch)or a project token) so an unusually long label wraps rather than pushing every input column away from shorter labels.
11. Sidebar Section-Header Alignment
When building a navigation sidebar whose interactive items have padded hover or active background boxes:
- Align section headers vertically with the
inline-startedge of the nav item icons (and top brand mark), never with the outer edge of the hover/active box. - Either match section header
padding-inline-startto the interactive items, or bleed the item hover/active box outward with a matching negative inline margin (margin-inline: calc(-1 * var(--item-px)); padding-inline: var(--item-px);) so brand mark, section headers, and nav icons share one vertical optical axis.
12. Focus-Ring Clipping & Forced-Colors Safety
When placing focusable controls inside overflow: hidden or overflow: clip containers (scroll strips, cards, collapsible panels, toolbars):
- Reserve container padding ≥
outline-width + outline-offseton all clipped edges, or use an insetoutline(outline-offset: calc(-1 * var(--focus-width))) so:focus-visiblerings are never clipped. - Windows High Contrast (
forced-colors: active): Browsers stripbox-shadowin forced-colors mode. Preferoutlineoverbox-shadowfor focus indicators; if an insetbox-shadowis used, pair it withoutline: 2px solid transparent; outline-offset: -2px;so forced-colors mode still renders a visible ring.
13. Scroll Chaining Containment
When building independently scrollable sidebars, drawers, popovers, dialogs, or hover cards:
- Declare
overscroll-behavior: containon the scroll container so wheel and touch scroll momentum stops at its boundary instead of scrolling the underlying page.
14. Tabular Numerals for Dynamic or Columnar Data
When rendering live counters, timers, numeric badges, progress percentages, or vertically aligned numeric table columns:
- Apply
font-variant-numeric: tabular-numsso digit updates do not trigger horizontal layout jitter and decimal points/columns stay vertically aligned. - This only works when the font provides the OpenType
tnumfeature. If it does not, verify by measuring digit widths (e.g.,1111vs0000); do not change the font family to get it.
15. Layout-Shift-Free Scrollbar Transitions
When building containers or document roots that toggle between non-overflowing and overflowing states (modals with scroll lock, expandable lists, route transitions):
- Prevent horizontal jumps on classic-scrollbar platforms (Windows/Linux) via
scrollbar-gutter: stable—orscrollbar-gutter: stable both-edgesfor centered containers/modals so reserving only the inline-end gutter does not nudge centered content off-axis (or compensate by measured scrollbar width when locking root scroll). Note that overlay scrollbars (macOS default, mobile) consume0pxregardless.
16. Active & Hover Font-Weight Jitter
When interactive horizontal nav items, tabs, or inline labels increase font-weight on :hover or active state:
- Reserve the bold text width—via an invisible bold
::aftercopy (content: attr(data-label); height: 0; overflow: hidden; visibility: hidden; font-weight: var(--active-weight)) stacked in the same grid cell, or via a variable font'sGRADaxis if the existing font supports it—so state changes never shift sibling positions.
17. Sticky Chrome scroll-margin-block
When sticky headers, toolbars, or footers can overlap keyboard-focused elements or #fragment anchor targets:
- Set
scroll-padding-blockon the scroll container (orscroll-margin-blockon focusable/anchor targets) to at least the sticky chrome's block size so focus and anchor jumps land fully visible.
18. Reduced Motion Ergonomics
When a component uses spatial or sliding transitions (collapsible drawers, sliding active nav indicators, hover card entrances/exits):
- Replace spatial movement with opacity cross-fades or instant state switches inside
@media (prefers-reduced-motion: reduce).
Pre-Ship Verification Checklist
Run each applicable pass/fail check before shipping:
- Tokens untouched: Zero unrequested changes to colors, fonts, radii, shadows, spacing scale, icon sizes, or UI patterns (Rule 2's re-derived
padding-inlineis the one intended exception). - Tokens bound: Every custom property the rules reference is mapped to an existing project value or has a
var()fallback; no declaration is invalid at computed-value time. - Contrast & exemptions: Every theme passes ≥
4.5:1normal text, ≥3:1large text and active UI/focus cues (including unselected but operable tabs and nav items), without overriding intentionally muted disabled or decorative elements. - Pill & button math: Intrinsic and fixed/
min-heightpills compute--pill/--edge(no999pxwith symmetric padding);.btn.pillcircular icons sit concentric;--icon-sizepreserves pixel-grid icons and outer pulls never collapse icon-label gaps; fallbacks gate on@supports (padding: calc(1lh + 1cap * pi)). - Wrapped-line icon: Forcing text to 2+ lines keeps the icon anchored to line 1 (matching heading
lhwhen adjacent to a heading). - Destructive targets: Close/delete controls stay visible without hover, meet ≥
24px(fine) / ≥44px(coarse) hit targets with zero target overlap, closable tabs enforce a minimum width (default8em), and hover-revealed⋮triggers stay visible under(hover: none). - Sidebar toggle & axis: Header/rail toggle buttons keep a constant
xcoordinate across clicks; brand mark, section headers, and nav icons share oneinline-startaxis. - Hover cards: Diagonal pointer travel never flickers, lateral travel to siblings is unblocked, and
Escape+ keyboard focus work. - Scrollable tabs: Edge fades track overflow on all devices; desktop chevrons stay
disabledat boundaries untilpointerleave; Tab focus clears overlays; nested radii are concentric. - Active indicator & weight stability: Active item stays distinct beyond low-contrast tint/weight, indicator bars clear scrollbars and
safe-area-inset/ rounded bezels, and bolding on hover/active causes zero sibling shift. - Timelines & forms: Equal top/bottom rail-to-circle gaps (
row-gapor cutout); horizontal forms use bounded-labelsubgridand stack vertically when narrow. - Focus, scroll, numbers & motion: Focus rings never clip inside
overflow: hidden/clipand remain visible inforced-colors: active; sticky chrome clears viascroll-padding-block/scroll-margin-block; scrollable overlays setoverscroll-behavior: contain; dynamic/columnar numbers usetabular-nums(font hastnum); scrollbar toggles avoid horizontal/centering shift (stable/stable both-edges); spatial animations reduce underprefers-reduced-motion: reduce.