CommunityCoding & Developmentgithub.com

ui-engineering-invariants

>- Enforces measurable optical, interaction, layout-stability, and accessibility invariants when building or reviewing web UI components (buttons, pills, inline icons, closable tabs, sidebars, hover cards, popovers, scrollable tab bars, active navigation indicators, timelines, multi-row forms, scrollable overlays, sticky chrome, and numeric readouts) strictly without prescribing or altering colors, typography, radii, spacing scales, or visual aesthetics.

What is ui-engineering-invariants?

ui-engineering-invariants is a Claude Code agent skill that >- Enforces measurable optical, interaction, layout-stability, and accessibility invariants when building or reviewing web UI components (buttons, pills, inline icons, closable tabs, sidebars, hover cards, popovers, scrollable tab bars, active navigation indicators, timelines, multi-row forms, scrollable overlays, sticky chrome, and numeric readouts) strictly without prescribing or altering colors, typography, radii, spacing scales, or visual aesthetics.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/acus9345/ui-engineering-invariants/tree/HEAD

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

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)) (never 1cap alone; Firefox shipped cap several releases before lh in v120)—and fall back to numeric equivalents derived from existing font size, line-height, and 0.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-radius resets to 0 and a pill renders square). Map --py, --bw, --icon-size, etc. to the project's existing values, or give each var() 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:1 contrast against its background.
  • Large text (≥ 24px regular or ≥ 18.67px bold): ≥ 3:1.
  • Interactive non-text UI (control boundaries required to identify hit areas, focus rings, meaningful icons, active indicators): ≥ 3:1 against 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: 999px with 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 --edge down for rounded rectangles (--r < var(--pill)), multiply by the unitless ratio r / pill using unitless tokens (dividing two <length> values inside calc() requires CSS Values 4 typed arithmetic, which has narrower browser support than lh, cap, and pi).

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-height half-leading, and do not resize existing icon-grid tokens (16px, 20px, etc.) to 1lh unconditionally.
  • Scope of change: This rule intentionally replaces the control's existing horizontal padding with a value derived from its existing --py and line-height. Keep --py and the project's spacing scale unchanged; only padding-inline is re-derived.
  • Derive horizontal padding from --py plus vertical half-leading, bind --icon-size to the design system's existing icon size (defaulting to 1lh), and pull only outer-edge icons inward via :first-child / :last-child so 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 .icon child and no text), matching both :first-child and :last-child is 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-end classes, because bare text nodes are invisible to :first-child/:last-child and would cause a leading/trailing icon to match both selectors and collapse the inner gap.
  • Script note: (1lh - 1cap) / 2 calibrates for Latin/alphabetic cap-height; for CJK-primary labels where glyphs fill nearly 1ic, use (1lh - 1ic) / 2 (or keep existing script-tuned padding tokens).
  • Composing Rule 1 + Rule 2 (.btn.pill): Set padding-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 by calc(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 to var(--py) - var(--px) - var(--edge) when intrinsic height wins and --icon-size is 1lh). On an outer-edge non-circular icon, keep --icon-pull so it retains --edge arc 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: center on the flex row.
  • Use align-items: start, anchor the icon to the first line with margin-top, and balance container padding/gap with --px: calc(var(--py) + (1lh - 1cap) / 2).
  • Match the first line's lh context: 1lh resolves against the icon's own computed line-height, not a sibling heading's. When an icon sits beside a heading (e.g., <h3>) whose font-size or line-height differs from the flex container, inherit or share the heading's line-height token (--first-line-lh) on the icon before computing margin-top: calc((var(--first-line-lh, 1lh) - var(--icon-size)) / 2) (or 0 when --icon-size equals --first-line-lh).
  • --first-line-lh must 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 the calc() 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 × 24px CSS pixels on fine pointers (WCAG 2.5.8 Target Size Minimum, AA) and ≥ 44px × 44px on 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: 8em unless 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-start offset 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. Radix HoverCard uses 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 Escape without 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).
  • 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 disabled until pointerleave before hiding it—never unmount it directly under an active pointer.
  • Keyboard focus clearance: Set scroll-padding-inline on 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:1 contrast 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-image or 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: subgrid scoped 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), or subgrid has 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-start edge 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-start to 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-offset on all clipped edges, or use an inset outline (outline-offset: calc(-1 * var(--focus-width))) so :focus-visible rings are never clipped.
  • Windows High Contrast (forced-colors: active): Browsers strip box-shadow in forced-colors mode. Prefer outline over box-shadow for focus indicators; if an inset box-shadow is used, pair it with outline: 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: contain on 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-nums so digit updates do not trigger horizontal layout jitter and decimal points/columns stay vertically aligned.
  • This only works when the font provides the OpenType tnum feature. If it does not, verify by measuring digit widths (e.g., 1111 vs 0000); 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—or scrollbar-gutter: stable both-edges for 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) consume 0px regardless.

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 ::after copy (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's GRAD axis 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-block on the scroll container (or scroll-margin-block on 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-inline is 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:1 normal text, ≥ 3:1 large 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-height pills compute --pill/--edge (no 999px with symmetric padding); .btn.pill circular icons sit concentric; --icon-size preserves 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 lh when 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 (default 8em), and hover-revealed ⋮ triggers stay visible under (hover: none).
  • Sidebar toggle & axis: Header/rail toggle buttons keep a constant x coordinate across clicks; brand mark, section headers, and nav icons share one inline-start axis.
  • 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 disabled at boundaries until pointerleave; 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-gap or cutout); horizontal forms use bounded-label subgrid and stack vertically when narrow.
  • Focus, scroll, numbers & motion: Focus rings never clip inside overflow: hidden/clip and remain visible in forced-colors: active; sticky chrome clears via scroll-padding-block/scroll-margin-block; scrollable overlays set overscroll-behavior: contain; dynamic/columnar numbers use tabular-nums (font has tnum); scrollbar toggles avoid horizontal/centering shift (stable / stable both-edges); spatial animations reduce under prefers-reduced-motion: reduce.

Related Skills