Design system

Design system authoring

Compose complete, inspectable CSS examples with the shared site components.

On this page

Keep the complete example, its source and its controls together. The shared UI supplies the surrounding presentation; the example owns every CSS prerequisite and measured relationship.

Use the brand guide for the mark, its gold, the typefaces and the voice. This handbook owns component interfaces and example construction.

#Import the shared components

Import primitives through explicit @master/internal-site/demo/*.astro or *.svelte subpaths in Astro and MDX. Astro renders the static structure; Svelte islands add measurements, playback and viewport controls. CSS-backed examples use the public compiler on the server and retain their complete source and generated output.

Demo

Interface: title, description, caption, controls, source, background, padding, align, frame

One example is one ui-tray: the head (title, description, controls), the ui-stage, the source (a code window and a closed DemoGeneratedCSS disclosure) and the caption. class and style apply to the stage; frameClassName styles the tray. Use frame="none" when the content already owns its frame, such as a DemoViewport browser or a comparison.

Use padding="none" when the child owns its own spacing. The stage centers its specimen; align="start" places it from the start edge. Framing must not add layout, containment, clipping or dimensions to the measured subject.

DemoSurface

Interface: elevation="flat" | "raised", native div props

A ui-sheet with the 10px radius; no implicit layout, padding or clipping. Explicit radius utilities can override it. The raised option uses the rise-1 elevation.

DemoItem

Interface: tone, variant, native div props

A ui-item tile with a 3rem minimum. Utilities set its geometry and layout. The default tone is neutral; blue, violet, amber, green and red are explicit teaching roles, always named by a legend or label.

DemoComparison

Interface: items with label and children, native div props

A ui-compare: one captioned stage per condition, side by side when there is room.

DemoMedia, DemoSwatch

Interface: Media accepts SVG props with an optional tone, or src and alt; swatches require label and accept optional value

Reusable SVG artwork and labeled color samples. Specimen text uses preset utilities directly.

DemoLabel, DemoLegend

Interface: Text; legend items with label and tone

Annotations accompany the subject instead of joining its layout.

DemoMeasure

Interface: label, children

Measures its content wrapper with ResizeObserver; the separate readout updates with width and height. Place it outside the demonstrated parent.

DemoAxes

Interface: inline, block, children

Labels a rightward horizontal axis and downward vertical axis around the example. Use custom labels only when those physical directions still match the scene.

DemoControls

Interface: label, variant="plain" | "segmented", children

A labeled group of native controls; segmented renders a ui-segmented track whose buttons carry aria-pressed. Place it in the tray head through controls.

DemoScrollArea

Interface: Native div props

Focusable region with bounded overflow.

DemoMotion

Interface: children

Explicit play, pause and replay using browser animations.

DemoViewport

Interface: title, document or src, responsive, chrome, widthPresets, theme, print, motion, initialTheme, inspect, height, maxWidth, sizing

An isolated iframe; width controls resize the actual viewport. Browser chrome (window dots, never an address) follows responsive; other previews stay plain. Add theme only when the lesson compares color schemes.

Fit uses the available width up to maxWidth. The slider and its live reading describe that same physical viewport. DemoContainer applies the same limit to its local wrapper while the page viewport stays unchanged.

DemoThemeComparison

Interface: name, title, html, css, caption, height, print

Compiles one trusted specimen into two independently themed, content-sized documents.

DemoPalette

Interface: Optional families

Fixed preset color inventory with native clipboard actions.

DemoCopyButton

Interface: value, label, optional feedback="value" | "compact", native button props

Reports a pending request, then the actual clipboard result, and retains keyboard focus. The default feedback includes the value; use compact when that value is already visible beside the control and reserve space for its short status.

DemoTokenTable

Interface: rows, optional descriptionTitle

Two-column document inventory; long tokens scroll inside the table.

DemoContainer

Interface: title, caption, children, maxWidth

A complete tray whose head holds keyboard-accessible width controls for a measured wrapper; children own containment.

DemoPageViewport

Interface: src, title, height

A trusted site example page in a real, scrollable viewport.

#Choose the smallest useful frame

background accepts plain (default), hatch, grid, dots, or checkerboard. padding accepts lg (default), sm, or none. Use none for an embedded viewport, a full-bleed scene, or a composition with its own padding.

#Fit the layers

Radii nest by the 4px tray inset: a 14px tray holds a 10px stage, code window or sheet; an 8px menu holds 4px items. Elevation follows one order, sink < flat < rise-1 < rise-1h < rise-2 < rise-3 < overlay, and every layer uses the --ui-elevation-* role instead of a hand-written shadow. A well sits below its surroundings with --ui-elevation-sink.

Keep a control's box, icon slot and label start steady through selection, pressing and copy feedback. Hover lifts half a pixel; pressing sinks into the well. Allow controls and their labels to wrap when text grows, and keep keyboard focus visible.

When an inline lesson needs more width than the document can provide, put a named, keyboard-focusable scroll region around the complete subject. Keep the subject's float, flex and sizing rules intact. The site's data-preview-scroll boundary uses Left and Right Arrow keys for horizontal scrolling; labels and controls stay outside that subject.

Keep select menus native with ui-select; it draws its own chevron without replacing the browser's picker or keyboard behavior. Use concise option labels and check that they remain fully visible at 200% text size.

Inspect icons and range handles at their rendered size in both modes. A small handle needs a stronger edge than a large panel to remain visible against its track. If an asymmetric icon needs optical centering, adjust only the glyph inside its stable slot. A disabled control keeps its selected position but loses the active text and contact shadow.

Client components can have an island host between the layout and the rendered control. Scope component classes without relying on a direct-child relationship across that boundary. Verify the rendered control before and after feedback appears.

#Minimal compositions

Every specimen below is available directly in MDX. The surrounding example owns geometry; these small compositions show where annotations and controls belong.

<DemoSurface className="p-md">  <DemoLabel>Layer</DemoLabel>  <p className="mt-xs mb(0) text-sm">Form follows function.</p></DemoSurface><DemoComparison items={[  { label: 'Before', children: <DemoItem>Before</DemoItem> },  { label: 'After', children: <DemoItem tone="violet" variant="outline">After</DemoItem> },]} /><DemoMedia tone="blue" className="w-full h-auto" /><DemoMedia src="/demo/landscape.svg" alt="Sun above mountains" /><DemoSwatch label="Subject" value="bg-blue-60" className="bg-blue-60" /><DemoAxes>  <DemoMeasure label="Container">    <div className="flex gap-sm">{/* measured layout */}</div>  </DemoMeasure></DemoAxes><DemoLegend items={[{ tone: 'blue', label: 'Subject' }]} /><DemoControls label="Alignment" variant="segmented">  <button type="button" aria-pressed="true">Start</button></DemoControls><DemoScrollArea aria-label="Layers" className="(height:10rem)">  {/* overflowing content */}</DemoScrollArea><DemoMotion>  <DemoItem className="(width:4rem) (height:4rem) (animation-name:rotate) (animation-duration:2s) (animation-timing-function:linear) (animation-iteration-count:infinite)" /></DemoMotion><DemoViewport title="Responsive layout" document={htmlDocument} responsive />

DemoComparison places each condition on its own captioned stage; use a native stacking parent when comparing vertically. DemoScrollArea intentionally establishes overflow. DemoViewport receives a complete HTML document with its own CSS, and supports native events, theme inspection and print preview. Its default upper limit is 1600px, so the preset lg breakpoint at 1280px is reachable. A narrow fitted viewport can be smaller than 240px; the slider reports that real width. Set maxWidth for a wider threshold when needed. Pass only trusted, site-authored documents; the iframe isolates layout and is not a security boundary. Set initialTheme="light" or "dark" to pin a specimen’s initial mode; omit it to follow the surrounding page. Controls become available after the preview is ready. Use the Reference recipes for compiled utility examples.

#Named viewport widths

Use widthPresets with responsive to expose meaningful boundaries alongside the range control. The first preset sets the initial iframe width; Fit returns to the available canvas width. Derive breakpoint values from the project’s active theme. Every preset changes the actual viewport, including when it is wider than the phone displaying it.

<DemoViewport  title="A breakpoint comparison"  document={htmlDocument}  responsive  widthPresets={[    { label: 'Below the boundary', width: breakpoint - 1 },    { label: 'Above the boundary', width: breakpoint + 1 },  ]}/>

Keep preset widths inside the range (240px through maxWidth) and use distinct, descriptive labels. Wide frames scroll inside the canvas; do not scale the specimen or rewrite the subject’s styles to imitate a media query. Syntax Tutorial uses the preset sm boundary for padding and conditional hover behavior.

#Keep behavior honest

Do not put layout, containment, transforms or clipping on a subject merely to center its label. Those properties can change the behavior being taught. Place controls outside the scene, and use an iframe for viewport-dependent examples.

#Size the canvas to the lesson

Use sizing="content" for normal-flow comparisons that stack on small screens. The frame follows its document’s natural height as images load or text wraps, so the reader can see every specimen without a second vertical scroll area.

Keep the default sizing="viewport" for fixed positioning, scrolling, viewport units and height-based conditions. In this mode, height defines the real viewport. Content sizing must not be used when the example’s height depends on the iframe’s own height.

<DemoViewport title="Image fitting" document={comparisonDocument} sizing="content" /><DemoViewport title="Sticky navigation" document={scrollingDocument} height={300} />

#Make positioning and paint boundaries explicit

Give a positioning example its containing block in the displayed HTML. Keep labels outside the tested layout; a label inserted into a flex row or text flow changes the lesson. Dashed outlines mark original slots and parent boundaries without adding border dimensions.

Stacking examples need actual overlapping positioned boxes. Show both the child and its parent context when teaching z-index. For isolation, put the comparison backdrop outside the tested element so readers can see which pixels are excluded from blending.

A clipping example should distinguish a scroll container from a clipping boundary. The viewport’s trusted specimen controls support data-scroll-container="element-id" with data-scroll-edge="start" or "end"; they call the element’s native scrollTo() method. Keep these controls outside the clipped element. Use ordinary DOM event listeners in standalone examples.

#Expose real scroll geometry

Keep a scrollport’s dimensions, overflow, track direction and snap candidates in the displayed HTML. The scroll recipes decorate that exact structure; they do not supply a missing track or scroll height through shared styles. Keep destination controls and position readings outside the scrollport.

Use nested outer and inner scroll areas to compare chaining. A native position readout makes the result visible even when the platform hides its scrollbars. data-scroll-readout="element-id" reports actual offsets; data-scroll-offset="target-id" with data-scrollport="container-id" and data-scroll-axis="x" or "y" reports the target’s inset from the scrollport edge.

A destination control with data-scroll-to="target-id" uses native scrollIntoView() with the target’s computed snap alignment. It preserves the surrounding document’s scroll position, including in browsers that ignore the nearest-container option. To demonstrate snap stops, use data-scroll-by="container-id" with data-scroll-distance="600": a relative request can stop at an intermediate snap point, while direct endpoint navigation can pass it. Relative snap-stop requests are immediate so their destinations are easy to compare. Smooth-scroll recipes follow the system’s reduced-motion preference.

#Measure flex sizing outside the layout

Flex recipes use the complete displayed HTML for parents, items, bases, gaps and constraints. Decorative outlines add no padding, minimum size or flex behavior. Keep axis labels and measurements outside the tested container so they cannot become extra flex items.

In a trusted iframe specimen, data-size-readout="element-id" reports the actual border-box size to one decimal place. A resize observer follows each measured element, including intrinsic sizes that change after a font loads. data-layout-axis="container-id" describes the computed main axis as inline or block, with reversal when applicable. The responsive iframe changes real media-query conditions.

Distinguish a starting basis from the final size. Grow factors distribute positive free space; shrink factors are weighted by the inner flex basis. Put a padded label inside a measured item when the lesson needs a simple outer-size ratio. For direction and order examples, native buttons with tabindex="0" expose the source focus sequence without a custom keyboard handler or positive tab indices.

#Distinguish alignment from distribution

Alignment recipes use the same layout paint as flex sizing examples. Author complete parents, tracks, items, gaps and automatic-size constraints in the displayed HTML. The shared paint adds outlines and tone without supplying any of those prerequisites. Name each comparison and keep its labels and readings outside the tested container.

Use data-alignment-axis="container-id" with data-axis-kind="main", "cross" or "both" to describe the relevant logical axes from the computed layout. In Grid, main maps to inline and cross maps to block; in Flexbox they follow the current flex direction. data-style-readout="element-id" with data-style-property="property-name" reports the native computed value, including the resolved grid columns.

data-position-readout="item-id" with data-position-origin="container-id" reports the item’s border-box offset from the container’s inner top-left corner. These are physical visible offsets, not a grid-area origin or unscrolled content coordinates. Negative values make unsafe alignment and actual scrolling visible. Pair offsets with dimensions, and explain which element or track is being aligned.

Demonstrate stretching with an automatic-sized item and an explicitly sized sibling. For safe alignment, compare content that fits with actual overflowing content; make the scrollport focusable and give it an accessible name. Preserve the native overflow so readers can inspect which edges remain reachable.

#Expose grid tracks and placement

The Grid recipes render the complete authored parent and children. Define explicit tracks, implicit sizing, flow, gaps and item placement in that HTML. The shared frame adds paint and external readings; it must not create tracks, supply missing items or establish Grid on an incomplete parent.

Use data-style-readout for grid-template-columns, grid-template-rows and grid-auto-flow, alongside the existing size and position readouts. The browser reports resolved track sizes, including implicit tracks. These readings do not distinguish explicit from implicit tracks on their own: explain that boundary in the example and name the relevant items. Line numbers count boundaries, so three explicit tracks have four lines.

Add data-round-pixels to a style readout when fractional pixel values would overwhelm the annotation. It rounds displayed pixel lengths to one decimal place and retains the full computed value in the output’s title. The measured layout is unchanged. When the canvas already contains its property readings, use an empty inspect list to omit duplicate toolbar values.

For dense packing, use spans that leave a real hole and later items small enough to fill it. Show source-order focus with native controls. For fractional tracks, make the available space definite when the lesson requires measured proportions. Keep track minimums separate from the content’s overflow treatment, and describe any deliberate clipping. Named-area examples must author both the area map and the track sizes; resizing changes actual iframe media queries.

#Show constraints and content

Sizing recipes render the complete displayed HTML, including the containing block, preferred dimensions, minimums, maximums and actual content. Measure the parent separately from the blue subject so a percentage has a visible reference. Give viewport-height examples a bounded iframe; a frame that grows with its content cannot demonstrate its own height units reliably. Enable viewport width controls for fluid wrappers even when there is no breakpoint.

Use real words for intrinsic sizing and actual media with known source dimensions for ratio and fitting examples. Keep the same content and overflow policy in a comparison. A scrollable overflow value can remove an automatic Flex minimum; use non-scrollable clipping when the lesson needs to isolate the effect of a zero minimum. A maximum does not imply growth or clipping, and matching bounds do not guarantee a square.

Spacing recipes keep labels and readings outside the tested layout. The neutral child exposes the content box inside blue padding; an outline marks the parent without adding a border. Compare content dimensions and physical insets using the existing size and position readouts. Author flow-root, Grid or Flex explicitly when required, and retain normal margin collapse when that is the lesson. Show inline/block behavior with a real writing-mode or direction change. Reserve space before external readings when a fixed-height specimen deliberately exposes visible overflow; keep that space outside the measured box.

#Preserve type, glyphs and inheritance

Typography recipes render the authored text, nesting, inline boxes and complete tables. Keep font size, weight, line height, spacing and alignment in the displayed HTML. Shared specimen paint adds a subtle outline and tone without changing those properties. Comparison names and computed readings sit outside the text context; they do not become extra line content or inherit the tested tracking.

Use the same words and reading width when comparing treatments. A computed line height is not a glyph height, and a family list is only a requested stack. For numeric features, measure actual glyph runs with data-size-readout and verify that the selected font supports the requested alternate. Use a proportional face for tabular-digit comparisons; a monospace default would hide the change.

data-font-status="Family name" reports the matching FontFaceSet entry as loaded, loading or unavailable. It does not infer success from font-family, claim that every character uses that face, or substitute a local font for a hosted resource. Whole-document specimens retain their stylesheet links and apply their authored body classes to the actual iframe body.

For optional platform properties, data-empty-value="Not exposed" supplies a clear label when the computed value is empty. An empty inspect list suppresses property inspection and does not create a toolbar on its own.

Let ordinary text previews grow with their content. Enable a real viewport control for fluid type formulas, even without a media query. Keep reset examples nested and baseline examples inline; a block placeholder cannot demonstrate vertical-align. Platform-specific rendering hints need visible support limitations, not a simulated pixel effect.

#Preserve text flow and reading paths

Text-flow recipes use the same type surfaces and external readings. Keep lang, dir, exact whitespace, nested writing contexts and complete overflow prerequisites in the displayed HTML. Never replace CJK or RTL content with an English placeholder, or insert visible annotation text into a whitespace-sensitive specimen.

Compare identical text and constraints. Use a genuine min-content box to demonstrate intrinsic wrapping differences, and an authored, named scroll region for intentional overflow. Native range geometry belongs in validation; it must not override line breaks or substitute synthetic text.

A truncation example needs a complete visible reading path when the hidden information matters. Use native disclosure controls with a descriptive summary, keep essential instructions visible, and verify keyboard focus and expansion. A tooltip alone is insufficient.

Use data-style-pseudo="::first-letter" with a style readout when the taught property applies to a pseudo-element. The same measurement component reads that native computed style. Do not infer a rendering-quality or performance improvement from an accepted hint.

#Isolate glyph paint

typeSpecimens(section, {  appearance: 'plain',  properties: ['text-decoration-line', 'text-decoration-style'],  measure: true,  caption: 'Compare the same words and font with two line styles.',})

Transparent text needs an authored visible paint source, such as a clipped gradient or a nonzero outline. Supply a solid fallback for print when backgrounds may be omitted. A plain specimen does not supply those prerequisites. Interactive subjects retain the shared keyboard focus ring.

#Preserve lists and generated content

Render the complete authored list, article and descendants. The plain text surface must not invent a counter name, reset value, marker, item or pseudo-element. Keep reading labels outside the authored article or list and report the property on the element that owns it. Native counter prefixes may remain unresolved counter() expressions in computed styles; inspect their rendered text instead of replacing them with scripted numbers.

Keep essential link names and instructions in HTML. A generated indicator supplements the native anchor and can enter its accessible name. Test the actual pseudo-element and preserve keyboard focus. For platform-dependent syntax, show the browser’s real support branch and label an authored fallback clearly.

<DemoExample page="counter-set" section="set-a-counter-on-one-item" /><DemoExample page="list-style-position" section="place-markers-inside-the-content-box" />

#Preserve background paint prerequisites

Author the image source, box dimensions, position, size, repeat behavior and backing color in the visible HTML. The plain specimen adds no image, border, padding, clipping or blend mode to the subject. Keep labels and computed readings outside its painted area.

For attachment, provide real overflowing content and a fixed-height iframe viewport. Test inner-panel and document scrolling independently; do not substitute transformed layers. Keep foreground text readable on its own opaque surface and describe platform-dependent fixed-background behavior in the exported prose.

The recipes link to complete authored examples; copy their HTML and any accompanying theme declarations. Use the guarded text-fill pattern for gradient lettering so unsupported browsers and print retain a solid foreground.

#Separate edge paint from layout

Supply border width, style and color explicitly. Compare the same box dimensions and state the box-sizing model: borders occupy layout space, while outlines and shadows do not. Use writing-mode comparisons when teaching logical edges. A transparent border keeps its used width; a none or hidden style does not on an ordinary box.

The plain specimen adds no border, outline, radius or shadow to the subject. Keep the live readings and labels outside it. Radius does not clip descendant content on its own; show the separate overflow rule when clipping is part of the example.

Compile authored theme declarations with their examples. The shadow recipe enables the preview's theme control explicitly, so users can compare actual token values in both modes. Raw paint values remain literal unless the author supplies a theme-dependent token or condition.

#Preserve source and fragment geometry

Table specimens need adjacent semantic cells and explicit cell borders. Computed spacing alone does not prove a gap: collapsed tables ignore it. Keep captions and annotations outside the measured seams.

For border images, use a loadable source with known dimensions and visible corner/edge patterns. Author its regular border, slices, image width and repeat behavior. Distinguish source coordinates from destination paint; native width and outset numbers are multipliers. Reserve actual layout space when outward paint needs room.

Inline-fragment specimens keep one real inline element inside an explicitly sized container. Supply its text, line height, padding and decoration. Let native wrapping create the fragments, and compare standard/prefixed support without replacing the text with separate boxes.

#Preserve media size and paint context

Give image specimens a loadable source with known natural dimensions and an explicit content box. Keep fitting and positioning independent from annotations. A source with a visibly round feature makes stretching distinguishable from cropping.

SVG specimens need real paths, a viewBox, viewport dimensions and explicit paint prerequisites. A computed stroke width does not report its final thickness after the viewBox transform. Keep non-scaling effects on the painted shape. Native controls provide state and accessible names for decorative icons; theme comparisons keep geometry constant.

#Preserve paint context and interaction

Filter examples need visible source detail and reserved room for paint outside the layout box. Use transparent artwork to distinguish an alpha-following drop shadow from a rectangular box shadow. Backdrop examples must include the actual background content and foreground panel, with explicit translucency and readable text.

Keep clipping and masking geometry in the authored HTML. Clip boundaries change pointer hit testing; masks on CSS boxes leave it unchanged. Place annotations and essential controls outside effects that could hide them. A fading scroll region needs real overflow, a native accessible name, keyboard focus and a description that stays readable.

Author blending groups and their complete backdrops explicitly. Use isolation only where the example calls for a bounded group. Whole-element opacity also fades descendants without disabling them; compare it with color alpha when only a surface should fade. Test native control behavior and restore appropriate paint in print.

#Preserve native shape wrapping

Shape specimens need a real float, explicit dimensions and adjacent inline content. Keep labels and measurements outside that formatting context. Author the painted shape separately: shape-outside changes wrapping without clipping or resizing the artwork. Name the reference box when margins could otherwise shift the shape’s coordinates.

Shape-margin expands the wrap contour within the float’s margin box. Reserve ordinary margins when a larger contour needs room. For image thresholds, use a loaded source with known alpha values and preserve its painted appearance across comparisons. Gradients and transparent same-origin images make threshold behavior visible without substituting positioned text.

#Preserve transform geometry and hints

Keep the original layout slot and pivot guides outside the transformed element. Use actual native controls for hover, focus and pressed states. Report client bounds separately from layout dimensions: getBoundingClientRect includes transforms, and SVG strokes can paint beyond its reported rectangle.

SVG examples need explicit viewBox, source coordinates and reference-box differences. For 3D scenes, author the perspective, transformed parent and translated child together. Do not add opacity, filters, isolation or clipping to that parent merely for decoration; grouping effects can flatten its descendants. Compare actual depth geometry as well as computed properties.

Will-change specimens expose the declared hint and its lifetime. Keep their controls visible, prepare the hint before the demonstrated change when appropriate, and release it afterward. A computed hint does not establish a performance gain. Timed interactions use the motion preference; their native states remain inspectable without interpolation.

#Preserve native transition timelines

For comparisons, keep distance and endpoints explicit. Use actual CSS transitions, including their waiting interval and state-specific easing. Gate both duration and delay for reduced motion, retain an immediate print state, and let native transitions finish when preferences change. Playback controls should pause only demos that explicitly opt into them.

#Preserve native animation phases

Keep the ordinary value, starting keyframe and ending keyframe distinct when teaching fill. Declare duration, delay and count explicitly; use the same path when comparing timing or direction. Preserve complete SVGs and leave status text stationary.

Playback controls operate on the browser’s actual CSS Animation objects. Retain finished one-shot timelines for replay, pause by default, and treat manual Play as an explicit motion preview. CSS play-state examples own their native checkbox and focus selectors instead; the toolbar must not override the property being taught. Their running rules require both screen media and the motion preference.

A timeline readout reports elapsed timeline time and native progress; a property readout still reports the authored CSS value. Keyframe-level easing may override the element’s easing for an interval. Neither readout is a performance measurement.

#Preserve native input and accessibility

Keep complete native controls, their options, labels and descriptions in the displayed HTML. Appearance, accent, caret and cursor change presentation; they do not supply activation or disabled behavior. Use an actual checkbox, disclosure or form action to make the result observable. Independent comparison specimens scope IDs together with their for, ARIA and local-link references so names and descriptions remain connected.

Pointer hit testing and keyboard access are separate. Preserve real overlay geometry and inherited child rules, and test both pointer input and keyboard activation. Observe native resize handles and text-selection gestures without setting dimensions or selections to manufacture the expected result.

Use touch input to test touch-action; mouse dragging cannot reproduce gesture arbitration. Keep named scroll regions and keyboard access, and describe the platform limits of resize and vendor drag behavior. A native drag readout only observes dragstart and dragend; it never makes an element draggable or cancels its events. Every example that depends on a vendor property needs an explicit support note and a portable alternative where available.

#Keep examples portable

DemoExample connects a utility page and section to its authored HTML and CSS snippets. The displayed structure should own every prerequisite needed to reproduce the behavior; shared recipes provide paint, annotations and controls. The Rust renderer compiles the actual utility classes. Keep the complete teaching explanation and framework-neutral example alongside the demo so Markdown and search exports remain useful. Wrap long HTML class attributes between complete utilities, keeping the taught property readable in the document column; never split an individual class across lines.

<DemoExample  page="clear"  section="clearing-both-left-and-right-floats"/>

#Examples with project CSS

Use DemoConfiguredExample when a preview needs project tokens or managed classes. The same project CSS and literal HTML supply the live iframe, visible code and complete generated CSS. Each preview owns its stylesheet and cannot change the surrounding document's theme, component classes or cascade.

<ProjectStyleExample name="tokens" /><ProjectStyleExample name="modes" /><ProjectStyleExample name="components" /><ProjectStyleExample name="layers" />

For a new lesson, supply its actual project CSS and complete HTML:

<DemoConfiguredExample name="project-spacing" title="A project spacing token"  source="@theme { --spacing-card: 1.5rem;  }"  html={'<article class="p-card">Collection details</article>'}  caption="p-card references --spacing-card." />

theme adds a real document-class switch; define explicit .light and .dark selectors outside @theme in the project CSS when teaching that behavior. The default has no controls. code={false} is for a gallery specimen whose usage link leads to the complete source. These are server components; only the existing iframe controls hydrate. Use trusted site-authored HTML with literal classes. Content-sized previews suit ordinary document flow; use DemoViewport directly for bounded scrolling, fixed positioning or viewport geometry.

shadow places the HTML and generated utility rules inside a real open shadow root. Foundation variables inherit from the iframe document. This variant previews styling; it does not load a framework or test runtime lifecycle. Keep that distinction in the caption and document runtime setup in the linked lesson.

A shadow-root specimen

<button type="button" class="px-md py-sm r-sm bg-blue fg-white">Hello Lit</button>
Generated CSS
@layer theme {  :root,  :host {    --color-blue-60: oklch(51.83% .2687 266.1)  }  :root,  :host {    --color-blue: var(--color-blue-60)  }  :root,  :host {    --color-white: oklch(100% 0 none)  }  :root,  :host {    --radius-sm: .25rem;    --spacing-sm: .75rem;    --spacing-md: 1rem  }}@layer utilities {  .bg-blue {    background-color: var(--color-blue)  }  .r-sm {    border-radius: var(--radius-sm)  }  .fg-white {    color: var(--color-white)  }  .py-sm {    padding-block: var(--spacing-sm)  }  .px-md {    padding-inline: var(--spacing-md)  }}
Generated utility CSS in an open shadow root; no framework runs in this preview.
<DemoConfiguredExample name="shadow-button" title="Shadow-root styling"  source="" html={'<button class="px-md py-sm bg-blue fg-white">Hello</button>'}  caption="Generated CSS inside a shadow root." shadow />

Used by Lit installation. The same default preview also supports the rendered markup in React and Vue.

For formal rules that need code without a live preview, ConfiguredExample accepts the same native-property support as the preview and includes complete generated CSS.

#Working recipes

Open the collection that matches the lesson. Each keeps its complete source and real browser behavior.

Project styles and layers

A small project vocabulary

p-card reads spacing, r-card reads radius, and fg-brand reads color. Each class retains a reference to its theme variable.
Read the lesson →

One spacing token, two consumers

Both elements have 1.5rem of padding. A change to --spacing-card applies to both consumers.
Read the lesson →

The same card in two modes

Theme switches the preview document’s light/dark class. The browser resolves the actual generated custom properties.
Read the lesson →

A component with native interaction states

Hover or focus the button to inspect its shared states.
Read the lesson →

Independent roles in one panel

Switch Theme to compare the color roles. The heading, action and progress fill share the brand color; information and action text have their own roles. The buttons demonstrate enabled and disabled states without saving data.
Read the lesson →

A local utility overrides the component

The same component is used twice. With the base layer order loaded, the normal padding utility wins in the second card.
Read the lesson →

A field that follows its content

The textarea uses native field-sizing. Minimum and maximum heights bound the enhancement; unsupported browsers retain a usable field.
Read the lesson →

Selection with a native selector

Check the option with a pointer or the Space key. :has(:checked) adds a border cue; the native checkbox carries the state.
Read the lesson →
Layout foundations

Viewport typography

View guide ↗

Viewport typography

Resize the actual iframe across md. The surrounding document keeps its own viewport.

Container grid

View guide ↗

A summary follows its container

Measuring container…

Release notes

Review the changes before publishing.

Status
Draft ready
Next step
Editorial review
Change the ancestor's width. The summary and status share a row from 28rem; the page viewport stays unchanged.

Container media object

View guide ↗

A component follows its container

Measuring container…
Collection / 024

Field notes

A small archive of places, textures and quiet details from the trail.

12 imagesUpdated today
Below 28rem of container width, the media stacks. At 28rem it keeps a 9rem width beside flexible text.

Fluid wrapper and measured object

View guide ↗

Fluid space, measured object

w-full · max-w-sm
FN
Field notes

Measured avatar. Flexible content.

One axis or both

View guide ↗

Choose one axis or both

(width:3.5rem) (height:3.5rem)
FN
w-full (height:3.5rem)
Fluid

Shrinkable content

View guide ↗

Keep long content within its cap

Measuring container…
FN
Project archive

field-notes-autumn-collection-final-v03.fig

The row stops at sm. The flexible text region can shrink below its content width.

Radius scale

View guide ↗

One scale, related surfaces

r-sm
Control
r-lg
Panel
r-2xl
Feature

Shape shortcuts

View guide ↗

Content-sized pill and width-led circle

w(48) (aspect-ratio:1/1) pill
These links share a destination. Their shape is independent of their native navigation behavior.

Workspace layout

Adjust the iframe viewport. Scroll inside the preview to see all content.
Typography and motion

Type hierarchy

View guide ↗

A readable type hierarchy

Size, spacing and text roles establish hierarchy with regular weight. The full body copy stays visible at every preview width.

Size and treatment

View guide ↗

One size, two type treatments

Both specimens have the same font size and content. font-3xl inherits the parent’s leading and tracking; text-3xl sets all three properties.

Finite entrances

View guide ↗

Two finite entrances

Both animations run once and start paused. Play and Replay control the native timelines. Reduced motion shows the content immediately without animation.

State transition

View guide ↗

A transition needs two states

The checkbox changes translateX from 0 to 96px. The 300ms transition starts after a 150ms delay. Reduced motion changes the state immediately; print keeps the initial position.

Dialog entrance

View guide ↗

Motion follows a real action

The dialog enters once on opening. Escape or Close details returns focus to its trigger. Reduced motion opens it immediately. Its modal boundary stays inside this preview.
Paint and color

Preset palette

Select a swatch to copy its variable.

blue
violet
Each swatch shows the fixed preset value in both themes.

Color roles

View guide ↗

One composition, two modes

Light
Dark
Both documents use identical classes. The active mode supplies the surface, line and text values.

Surface hierarchy

View guide ↗

Surface hierarchy

Light
Dark
Color separates these surfaces. This example adds no shadow.

Line roles

View guide ↗

Visible boundaries

Light
Dark
The line role selects a color. Width and style still need an explicit declaration.

Text roles

View guide ↗

Readable hierarchy

Light
Dark
The archive action is natively disabled. Inverse text is paired with its inverse surface.

A fixed hue

Light
Dark
General hue aliases keep the same swatch in both schemes. Use text hue aliases for adaptive readable foregrounds.

Foreground color by role

Light
Dark
fg-text-blue uses the foreground-oriented alias. Check the actual foreground and surface together.

Quiet elevation

View guide ↗

Quiet separation

Light
Dark
shadow-sm uses the same offsets across these modes, with different edge and shadow colors.

Interactive elevation

View guide ↗

Depth follows interaction

Light
Dark
A native link supports pointer and keyboard focus. The focus outline remains visible; printing removes the shadow.
Namespace comparisons
NamespaceConsumers
duration-*
  • animation-
  • animation-delay-
  • transition-
  • transition-delay-
spacing-*
  • border-spacing-
  • bottom-
  • col-gap-
  • gap-
  • inset-
  • ix-
Show 57 more keys
  • ixe-
  • ixs-
  • iy-
  • iye-
  • iys-
  • left-
  • m-
  • mb-
  • ml-
  • mr-
  • mt-
  • mx-
  • mxe-
  • mxs-
  • my-
  • mye-
  • mys-
  • outline-offset-
  • p-
  • pb-
  • pl-
  • pr-
  • pt-
  • px-
  • pxe-
  • pxs-
  • py-
  • pye-
  • pys-
  • right-
  • row-gap-
  • scroll-m-
  • scroll-mb-
  • scroll-ml-
  • scroll-mr-
  • scroll-mt-
  • scroll-mx-
  • scroll-mxe-
  • scroll-mxs-
  • scroll-my-
  • scroll-mye-
  • scroll-mys-
  • scroll-p-
  • scroll-pb-
  • scroll-pl-
  • scroll-pr-
  • scroll-pt-
  • scroll-px-
  • scroll-pxe-
  • scroll-pxs-
  • scroll-py-
  • scroll-pye-
  • scroll-pys-
  • shape-margin-
  • top-
  • translate-
  • word-spacing-
Code and table patterns
TokenCSS
@layer(components)@layer components
@motion-reduce@media (prefers-reduced-motion: reduce)
@supports(<feature>)@supports (<feature>)
Syntax and viewports
Utility behavior recipes

Flow4 recipes

Clear the right boundaryclear

Clearing right floats

The blue block clears the right float. Its text still wraps around the taller left float, whose box overlaps the blue background.
Follow a native floating shapeshape-outside

Wrap text around a circle

The artwork and float box are explicit. Shape-outside changes the space available to adjacent inline content without clipping the artwork.
Reserve a shape’s surrounding spaceshape-margin

Reserve room for a larger shape margin

The same painted circle and ordinary margins are preserved. Shape-margin expands the wrap boundary within the float’s margin box.
Extract wrapping from image alphashape-image-threshold

Set the alpha threshold

Image paint is unchanged. The browser extracts the wrap shape from pixels whose alpha exceeds the threshold; a basic shape uses its own geometry.

Flexbox & grid10 recipes

Arrange on two axesalign-items

Align items on the cross axis

Compare the blue item with the violet sibling. Automatic sizes can stretch; explicit sizes keep their dimensions.
Measure distributed free spaceflex-grow

Let an item grow

Grow factors divide the extra space, not the final widths. Both items keep their authored bases and padding.
Preserve the source sequenceorder

Keep source order meaningful

Focus Source 1, then press Tab. The browser follows the source sequence; CSS order changes only these items’ visual positions.
Separate track and item alignmentplace-content

Use separate axis values

The fixed track group moves within the larger grid container. Its column widths, row heights and minimum gaps stay unchanged.
Stretch automatic dimensionsalign-items

Stretch automatic-sized children

Compare the blue item with the violet sibling. Automatic sizes can stretch; explicit sizes keep their dimensions.
Keep overflowing content reachablejustify-content

Keep overflowing content reachable

The overflow is real and scrollable. Safe centering preserves access to the start; unsafe centering loses the portion before the scrollport.
Distinguish explicit and implicit tracksgrid-auto-columns

Size implicit columns

The violet first column is explicit. The blue column and its following sibling use the implicit-column size.
Pack cells without reordering focusgrid-auto-flow

Fill gaps densely

Compare the position of 03, then focus 01 and press Tab. Visual packing changes; source-order keyboard traversal does not.
Map responsive named regionsgrid-template-areas

Apply conditionally

Header, Nav and Content keep their area names. The parent supplies both the region map and its track sizes.
Compare flexible track minimumsgrid-template-columns

Control a track’s minimum

The content stays 192px wide in both examples. The blue cell clips excess content when its track is allowed to shrink.

Sizing & spacing6 recipes

Expose the box modelpadding
Read related documentation ↗

Add padding on every side

Blue surrounds the neutral content. The content inset reports physical left and top padding; the padding value lists the physical sides.
Measure intrinsic content widthswidth

Use intrinsic width keywords

The dashed outline is the authored containing block. Read the actual blue border-box width alongside its parent.
Release an automatic flex minimummin-width

Allow flexible children to shrink

Compare the preferred width with its actual lower bound. The blue measurement includes padding but excludes its decorative outline.
Follow logical padding directionspadding
Read related documentation ↗

Set inline or block padding

Blue surrounds the neutral content. The content inset reports physical left and top padding; the padding value lists the physical sides.
Distinguish ratio from fixed dimensionsaspect-ratio

Pair with one explicit axis

The ratio is a preferred constraint. An automatic dimension can follow it; two definite dimensions take precedence.
Observe constrained native resizingresize

Restrict resizing to one axis

Drag the native resize handle where supported. The readout measures the real control box as it changes. Editing and scrolling remain available when handles are absent.

Position & scrolling5 recipes

Keep context in viewposition

Positioning elements as sticky

Focus the list and scroll with the arrow keys. The blue row sticks to its top edge after the first row scrolls away.
Compare local paint orderz-index

Prefer local stacking contexts

Z-index values are compared within their own stacking context. Raising the child to 99 cannot lift its parent above sibling 1.
Separate clipping from scrollingoverflow

Clip without scrolling

The buttons call the same native scroll API as the hidden example. Clip remains at its original scroll position.
Reserve a viewing insetscroll-padding

Reserve space for fixed headers

The scroll container owns the viewing inset. Choose an interior target to see its alignment without reaching the track’s boundary.
Observe native scroll chainingoverscroll-behavior

Contain nested scrolling

Send the inner list to its bottom edge, then continue scrolling over it. Compare the outer y value; the iframe keeps both experiments separate from the document.

Typography13 recipes

Preserve an inherited resetfont-style

Reset font style

The blue child resets its inherited slant. The surrounding words keep their italic style.
Measure actual digit advancesfont-variant-numeric

Align tabular numbers

The selected font must support the feature. Compare actual digits as well as computed values; equal digit counts make advances comparable.
Compare inherited line heightsline-height

Use explicit values

The readout is the computed line height, not glyph height. Mixed sizes, inline objects and inherited values can affect the final line box.
Align against a native text baselinevertical-align

Align icons with text

These are actual inline boxes and table cells. The annotations are outside the formatting context and cannot become extra inline content.
Separate wrapping from intrinsic widthoverflow-wrap

Allow breaks anywhere

Compare the authored constraints and actual box sizes. Emergency breaks and intrinsic width are separate parts of text layout.
Follow native column progressionwriting-mode

Use vertical right-to-left flow

Writing mode sets line orientation and block progression. The authored dimensions make the column direction visible.
Separate glyph fill from foregroundtext-fill-color

Use the current color

Glyph fill is independent of the foreground color. The plain surface adds no fill, stroke or background to the subject.
Compare paint without resizing texttext-stroke-width

Set text stroke width

Compare the same glyphs at the same font size. The width changes the painted edge; box measurements expose the unchanged layout geometry.
Preserve running counter scopecounter-set

Set a counter on one item

The readout follows the element that sets the counter. Reset, increment and set are separate operations; following elements continue from the resulting value.
Compare native hanging markerslist-style-position

Place markers inside the content box

Identical content and width reveal the wrapped-line alignment. Marker position is independent of the surrounding label and property readout.
Keep meaning in the link textcontent
Read related documentation ↗

Add indicators for external links

The readout observes the actual ::after pseudo-element. The link remains a native, keyboard-accessible anchor with meaningful text in the HTML.
Preserve native inline fragmentsbox-decoration-break

Clone

One inline element creates real line fragments. The readings expose standard and WebKit property support; the container controls wrapping.
Keep selection boundaries explicituser-select

Select a whole value

Use the platform’s text-selection gesture on the authored content. Selection rules do not disable native control actions or protect text from copying.

Color & media8 recipes

Separate paint from positioningbackground-origin

Choose the background positioning area

Origin determines the image’s positioning area. Clipping stays separately authored, so positioning and painting boundaries remain distinct.
Compare image fit and cropbackground-size

Cover a frame

The readout reports the computed size, including keywords. The artwork’s visible edges expose the actual fit, crop or distortion.
Observe native background attachmentbackground-attachment

Attach to scrollable content

Scroll both the inner panel and this preview page. Fixed attachment refers to the iframe viewport; local refers to the scrollable content. Actual paint support can vary by platform.
Keep the image box independent of fitobject-fit

Cover a fixed frame

The source is 320 × 200. The measured box belongs to the image element; fitting changes the content inside it.
Place content within its cropobject-position

Use precise positions

The 240 × 100 image box contains a 240 × 150 cover image. Positioning changes its crop without moving the element.
Compare theme and palette paintfill
Read related documentation ↗

Use theme colors

The shapes and paint are explicitly authored. Fill is inherited independently of stroke; controls retain their native accessible names.
Distinguish SVG units from screen paintstroke-width

Pair width with stroke color

The 24 × 24 viewBox scales into a 96 × 96 viewport. Computed width and final painted thickness are different measurements.
Compare SVG transform reference boxestransform-box

Choose the transform reference box

The complete HTML or SVG preserves source geometry. Reference boxes control percentages and pivots; client bounds use getBoundingClientRect and do not include an SVG stroke’s full paint.

Edges & effects11 recipes

Isolate an external backdropisolation

Create a stacking context

Both blue backgrounds sit outside the tested section. An isolated section prevents its purple child from blending with that external backdrop.
Show the layers beneathbackdrop-filter

Blur content behind an element

The complete composition supplies the backdrop and panel. Filtering changes pixels behind the panel, while its own text remains sharp.
Separate curves from clippingborder-radius
Read related documentation ↗

Use a radius token

Compare the painted corners with the measured layout box. Radius, aspect ratio and overflow are separate properties.
Inspect mode-specific shadow layersbox-shadow
Read related documentation ↗

Customize mode-specific tokens

These are the browser’s actual shadow layers. The measured box excludes their paint; theme tokens may resolve differently in each mode.
Compare native shared table edgesborder-collapse

Match border spacing to the mode

Cell borders and spacing are explicitly authored. Compare the actual shared seams as well as the computed table properties.
Separate source slices from border paintborder-image-slice

Slice the source image

The 96 × 96 source uses 24-unit corners. Slice boundaries belong to the source; painted widths belong to the destination border.
Fit actual patterned edge tilesborder-image-repeat

Round repeated edge slices

The first repeat value controls top and bottom edges; the second controls left and right. The source pattern makes individual tiles visible.
Follow transparent source silhouettesfilter

Use drop shadow for transparent images

The source and its dimensions are explicit. Filters change the painted group; the measured layout box stays unchanged.
Separate clipped paint from layoutclip-path

Clip with an inset

The outer outline marks the original box. Clipping changes paint and hit testing without changing layout dimensions.
Fade a real scrollable regionmask-image

Fade overflowing media

The mask changes painted opacity. The CSS box keeps its dimensions and hit area; annotations remain outside the mask.
Bound blending with an explicit groupmix-blend-mode

Blend an element with its backdrop

The explicitly isolated group contains both backdrops. Foreground geometry and source colors are identical in each comparison.

Motion13 recipes

Choose deliberate snap stopsscroll-snap-stop

Use sparingly

Reset, then Advance by the same immediate 600px request. Always stops a directional scroll at the next eligible point; normal allows it to pass.
Make time visibleanimation-direction

Play alternately

Play opts into the actual CSS animation. Pause retains its time; Replay restarts even a finished one-shot. Readouts show native timeline time and progress, including delay and fill.
Keep layout and transform bounds distincttransform

Move an element

The authored guide keeps the original layout slot visible. Client bounds follow the transformed element’s getBoundingClientRect, not its unchanged layout dimensions.
Anchor a scale to its pivottransform-origin

Set the pivot point

The reference dimensions, pivot and transform are authored together. Markers stay outside the transformed element; the guides reveal displacement while client bounds report transformed width and height.
Expose native 3D flatteningtransform-style

Flatten nested transforms

The parent, front layer and perspective form a real 3D context. Compare the child’s geometry: grouping effects can flatten it even when the computed keyword remains preserve-3d.
Select which changes interpolatetransition-property

Limit what can animate

Each control changes the same authored endpoints. Only properties in the selected list interpolate; unrelated changes remain immediate.
Compare travel distance and durationtransition-duration

Match duration to distance

The control, travel distance and easing stay explicit. Duration is the interpolation interval, independent of any start delay.
Stagger real sibling transitionstransition-delay

Stagger sibling elements

The visible control changes the endpoint before the layer starts moving. Each changing child owns its duration and delay; they are not inherited.
Compare progress through timetransition-timing-function

Choose an easing curve

The native transition keeps its authored duration and endpoints. Compare how the curve distributes progress, or how steps advances at discrete boundaries.
Separate delay from active progressanimation-delay

Delay animation start

Play opts into the actual CSS animation. Pause retains its time; Replay restarts even a finished one-shot. Readouts show native timeline time and progress, including delay and fill.
Retain native start and end statesanimation-fill-mode

Apply both before and after states

Play opts into the actual CSS animation. Pause retains its time; Replay restarts even a finished one-shot. Readouts show native timeline time and progress, including delay and fill.
End within a fractional cycleanimation-iteration-count

Specify a number of iterations

Play opts into the actual CSS animation. Pause retains its time; Replay restarts even a finished one-shot. Readouts show native timeline time and progress, including delay and fill.
Apply easing at the keyframe intervalanimation-timing-function

Match easing to intent

Play opts into the actual CSS animation. Pause retains its time; Replay restarts even a finished one-shot. Readouts show native timeline time and progress, including delay and fill.

Interaction9 recipes

Keep controls accessiblescreen-readers
Read related documentation ↗

Label icon-only controls

Visible annotations explain the actual accessible name or description. Use Tab to reach the visible native control; its hidden label is not a separate focus target.
Preserve interaction under opacityopacity

Fade an entire element

Opacity changes the entire painted group. Native controls keep their names and keyboard behavior; color alpha changes only that color.
Prepare and release an actual browser hintwill-change

Reset when the hint is no longer useful

The readout observes the actual hint. Native controls remain visible and operable; this specimen does not measure speed or prove compositing-layer promotion.
Pause decoration while editinganimation-play-state

Pause nonessential motion

The native checkbox and authored selectors control the child’s CSS play state. Pausing preserves its time. Reduced motion keeps it paused; print removes the animation.
Keep the platform control intactaccent-color

Set the accent color

Use the actual checkbox, radio group and range. The browser and platform decide how a requested accent is painted; the controls retain their native keyboard behavior.
Restyle a native selectappearance

Remove default styling

The full authored select and its options remain native. Change its value with the platform picker or keyboard; appearance changes paint without replacing the accessible label.
Separate pointer targeting from focuspointer-events

Let clicks pass through an overlay

Pointer hit testing and keyboard access are independent. Use the real checkbox or reset button to verify the action; transparent overlays keep their authored geometry.
Distinguish touch gestures from scrollingtouch-action

Disable browser gestures on a custom surface

Swipe on a touch device to test native panning. Keyboard scrolling remains available. The rules allow or restrict browser gestures; no custom drawing or drag handler is supplied.
Observe actual native drag startsuser-drag

Prevent dragging media

Try a native pointer drag in a supporting browser. The event readout observes actual drag starts; vendor property support and touch behavior depend on the platform.