# Master CSS > A CSS language and framework for rapidly building beautiful websites and design systems with rule-based CSS-in-class. --- # Master CSS Vite: one plugin for every rendering mode Source: https://rc.css.master.co/en/blog/bootstrapping-master-css-with-vite Summary: A cleaner Vite integration for runtime rendering, static rendering, pre-rendering, and progressive rendering. Vite is one of the best foundations for modern frontend work: fast startup, predictable module graph, first-class plugins, and a build pipeline that is easy to extend without making the application feel heavy. `@master/css.vite` brings Master CSS into that pipeline as a first-class Vite integration. Instead of choosing between several setup guides, manual runtime imports, scanning scripts, and HTML post-processing steps, you install one plugin and choose the rendering model that matches your application. The goal is simple: keep Master CSS authoring as direct as markup, while letting Vite own the integration work. --- ## One plugin, four rendering modes The original Vite integration focused on Static Rendering. It worked well for projects that wanted a compiled stylesheet, but the rest of the Master CSS rendering story still required manual setup. The new `@master/css.vite` plugin unifies the modes behind one entry point: - `runtime`: injects the Master CSS runtime and config so styles can be generated in the browser. - `static`: wires Master CSS stylesheet imports into the static rendering workflow. - `pre-render`: renders HTML output and injects the CSS needed by those documents. - `progressive`: combines pre-rendered first-response CSS with the runtime engine for dynamic UI. That matters because not every Vite app has the same shape. A design system playground, a documentation site, a SPA, and a partially pre-rendered app should not be forced into the same CSS delivery strategy. Master CSS now lets the Vite project choose. --- ## Install it If you don't have a project yet, create one using `npm create vite@latest my-app`. ```bash action=install @master/css.vite@rc ``` Then register the plugin: ```js name=vite.config.js import { defineConfig } from 'vite' import masterCSS from '@master/css.vite' // [!code highlight] export default defineConfig({ plugins: [ masterCSS() // [!code highlight] ] }) ``` By default, the plugin uses `runtime` mode. That is the most forgiving way to start: Master CSS reads classes in the browser, generates the required rules, and keeps working as your UI changes. Run the Vite dev server and start writing Master CSS classes: ```bash action=run dev ``` --- ## Choose the right mode ### Runtime Use runtime mode when you want the simplest integration and maximum flexibility. It is a strong default for SPAs, prototypes, internal tools, and applications where classes can appear after hydration. ```js name=vite.config.js import { defineConfig } from 'vite' import masterCSS from '@master/css.vite' export default defineConfig({ plugins: [ masterCSS() ] }) ``` ### Static Rendering Use static mode when your classes are visible in source and you want a compiled CSS asset before runtime. This is the closest mode to traditional utility-first build workflows. ```js name=vite.config.js import { defineConfig } from 'vite' import masterCSS from '@master/css.vite' export default defineConfig({ plugins: [ masterCSS({ mode: 'static' }) ] }) ``` ### Pre-rendering Use pre-render mode when Vite emits HTML that can be styled before the browser runs JavaScript. The plugin renders the matching CSS and injects it into the document. For rendered pages, the critical CSS stays inline in `style#master-css`. The page hydration manifest is externalized as a hashed JSON asset and referenced from `data-master-css-hydration-manifest`, so the HTML does not grow with the runtime handoff data. ```js name=vite.config.js import { defineConfig } from 'vite' import masterCSS from '@master/css.vite' export default defineConfig({ plugins: [ masterCSS({ mode: 'pre-render' }) ] }) ``` ### Progressive Rendering Use progressive mode when you want the first HTML response to carry the CSS it needs, while the runtime continues to support client-only state, late-rendered components, and dynamic UI. ```js name=vite.config.js import { defineConfig } from 'vite' import masterCSS from '@master/css.vite' export default defineConfig({ plugins: [ masterCSS({ mode: 'progressive' }) ] }) ``` This is the mode that best represents the Master CSS rendering model: render what can be known early, keep the runtime for what becomes known later. In progressive mode, the runtime imports the page hydration manifest as a JSON module when it starts. Do not add a preload hint for that JSON file: the browser can already paint from `style#master-css`, and the manifest is only needed for the runtime to adopt those rules instead of rebuilding them. --- ## What the plugin handles `@master/css.vite` is not just a wrapper around an import. It participates in the Vite pipeline: - resolves the compiled MasterCSSManifest as a virtual module; - detects common Vite entry modules; - keeps the default stylesheet as an explicit `@import "@master/css"` in app CSS; - injects the runtime where runtime behavior is enabled; - handles static rendering output; - pre-renders HTML when the selected mode requires it; - externalizes page hydration manifests for pre-rendered and progressive HTML; - applies FOUC avoidance for runtime-first rendering. That is the difference between "Master CSS works in a Vite app" and "Master CSS feels like a Vite-native tool." --- ## Built for Vite-powered frameworks Vite is also the build foundation for many frameworks. `@master/css.vite` is the lower-level integration that makes the core Vite workflow work well, while framework packages can provide a more native setup when the framework has its own conventions. [Nuxt](/guide/installation/nuxtjs) uses a module: ```ts name=nuxt.config.ts export default defineNuxtConfig({ modules: [ '@master/css.nuxt' // progressive by default [!code highlight] // ['@master/css.nuxt', { mode: 'static' }] // ['@master/css.nuxt', { mode: 'runtime' }] // ['@master/css.nuxt', { mode: 'pre-render' }] ] }) ``` [Astro](/guide/installation/astro) uses an integration: ```ts name=astro.config.ts import masterCSS from '@master/css.astro' export default defineConfig({ integrations: [ masterCSS() // 'progressive' [!code highlight] // masterCSS({ mode: 'static' }) ] }) ``` --- ## A better default for Vite projects The value of this release is not only that setup is shorter. It is that the rendering strategy is now explicit and local to the Vite config. Start with runtime mode when you want speed and flexibility. Move to Static Rendering when your class graph is source-visible and you want compiled CSS. Use Pre-rendering when the HTML is already available at build time. Choose Progressive Rendering when you want the first page response to be styled early without giving up runtime behavior. That is the kind of choice a build tool should enable: one integration, multiple delivery strategies, and no extra application code when you change modes. For full setup details, see the [Vite installation guide](/guide/installation/vite) and the [rendering modes guide](/guide/rendering-modes). --- # Introducing the Master CSS Next.js Source: https://rc.css.master.co/en/blog/master-css-next Summary: The Next.js Adapter brings Progressive Rendering into the build pipeline, with Turbopack support for Static Rendering. Today we are introducing `@master/css.next`, the official Master CSS integration for Next.js. The headline is Progressive Rendering through the Next.js Adapter API. The adapter plugs into the Next.js build pipeline, receives the final static and pre-rendered HTML outputs, renders the Master CSS rules each document needs, and writes them back into the page as `

Hello

``` The browser can paint the heading from `style#master-css` before the runtime does any work. When the runtime starts, it imports the hashed JSON manifest, maps the native CSS rule back to `font:48px`, and continues handling later dynamic classes from the same managed stylesheet. If a page has no generated Master CSS rules, the adapter does not need to attach a manifest URL. This page hydration manifest is separate from the project manifest and from the `buildReport` option in `@master/css.next`. When enabled, `buildReport` writes `.next/master-css-build-report.json` with details about rendered files; it is not the route-level JSON used to hydrate `style#master-css` in the browser. --- ## Adapter integration The new adapter is registered in `next.config.js`, and Next.js calls it when the full build output is available: ```js name=next.config.js import { withMasterCSS } from '@master/css.next' /** @type {import('next').NextConfig} */ const nextConfig = withMasterCSS({ // your Next.js config }) export default nextConfig ``` This turns Progressive Rendering from a post-build convention into a framework-level integration. Master CSS no longer needs the application to maintain a second render script, and the integration can follow the typed Next.js output contract as it evolves. --- ## What improves ### Faster first paint The critical CSS for a pre-rendered page is already in the HTML response. The browser does not need to wait for the Master CSS runtime to boot before styling the first screen, which reduces the risk of flash of unstyled content. ### Route-level CSS output The adapter renders CSS from each HTML document, not from the entire source tree. A page only receives the class rules needed by that page's first HTML output. That is especially valuable for documentation sites, marketing pages, blogs, dashboards with static shells, and large App Router applications where different routes use very different surfaces. ### Runtime flexibility stays available Progressive Rendering does not remove the runtime engine. It gives the first response the CSS that can be known during the build, then lets the runtime continue tracking client-only state, late UI, and dynamic class names after hydration. ### Same authoring model There is no second syntax and no separate critical CSS file to maintain. You still write Master CSS classes in markup, and the adapter decides what should be present in the first HTML response. --- ## Install it For the full setup, follow [Progressive Rendering in Next.js](/guide/installation/nextjs). If your project needs a source-scanned CSS build instead, use [Static Rendering in Next.js](/guide/installation/nextjs/static-rendering). Import Master CSS from the stylesheet your app already loads. This stylesheet also serves as the project CSS entry: ```css name=app/globals.css @import '@master/css'; ``` Install Master CSS and the Next.js adapter: ```bash action=install @master/css@rc @master/css.next@rc ``` Keep the root layout focused on the global stylesheet: ```tsx name=app/layout.tsx import './globals.css' export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ) } ``` The Next.js adapter injects the runtime through the build tool and loads the canonical project-level MasterCSSManifest automatically. React apps outside build-tool integrations can use `@master/css-runtime` directly. Then register the adapter: ```js name=next.config.js import { withMasterCSS } from '@master/css.next' /** @type {import('next').NextConfig} */ const nextConfig = withMasterCSS({ /* your Next.js config */ }) export default nextConfig ``` Development uses the runtime engine directly for fast refresh. Run a production build to verify that ` ``` (x) Do not add a preload hint for this JSON file. The page hydration manifest is runtime handoff data. It lets the runtime adopt the rules that already exist in `style#master-css`, but it is not required for the browser to paint the first screen. Let the runtime import it when hydration starts. If that import fails or the data is invalid, the runtime rebuilds from connected DOM classes. This is different from runtime project manifests. A runtime-only page needs its project manifest before it can interpret classes. A progressive page already has the first-response rules in `style#master-css`, so its page hydration manifest only describes CSS that was already rendered into that one HTML response. --- ## Benefits Preloading critical assets can improve the following metrics: 1. **First Contentful Paint (FCP)**: Preloading critical assets helps accelerate the loading of essential scripts, such as JavaScript, resulting in faster FCP. This means that the main content of the webpage can be displayed more quickly in the user's browser, enhancing their perception and experience. 2. **First Meaningful Paint (FMP)**: By preloading critical scripts, the browser can start parsing and rendering the script earlier, leading to faster FMP. This allows users to see meaningful content more rapidly, improving the visual presentation of the page. 3. **Time to Interactive (TTI)**: Preloading critical scripts reduces waiting time for users, resulting in a faster Time to Interactive. When the critical script has been downloaded and is ready, users can interact with the webpage more quickly, providing a better user experience. Preloading critical scripts enhances the download and execution speed of the scripts, thereby improving metrics such as First Contentful Paint, First Meaningful Paint, and Time to Interactive. --- # Rendering Modes Source: https://rc.css.master.co/en/guide/rendering-modes Summary: Understand how the rendering modes of Master CSS work and enhance your website's performance. ## Overview Master CSS integrations choose how generated rules reach the browser. The same project CSS entry graph can be used by runtime rendering, static rendering, server rendering, and progressive hydration. | Mode | Description | |---------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------| | `'runtime'` | Starts `CSSRuntime` in the browser, loads the project manifest, observes connected elements, and ensures generated rules as class names appear. | | `'static'` | Scans source files, replaces `@import '@master/css'` in managed CSS entries, prunes native CSS, and generates CSS from the project CSS entry graph. | | `'pre-render'` | Renders HTML output and injects the CSS required by the rendered class names. This mode is usually owned by SSR/SSG integrations. | | `'progressive'` | Combines server-rendered first-page CSS, a hydration manifest, and client-side runtime adoption for classes that appear after the initial HTML. | Every mode uses the same cascade layer model. The default `@master/css/base.css` stylesheet declares `@layer theme, base, defaults, components, utilities;`, while generated rules are emitted into layer blocks without redeclaring the global order. Runtime and progressive rendering optimize what CSS is delivered up front. They do not make browser style calculation free: when a highly interactive screen creates many first-time utility rules during one interaction, the browser still needs to account for those new stylesheet rules before it can paint the updated DOM. For page-level CSS size and delivery measurements, see the [benchmarks](/guide/benchmarks). --- ## Runtime Rendering Master CSS Runtime relies on the lifecycle of individual elements. Only the Master CSS class names connected to the DOM tree will generate corresponding CSS rules so *browsers can calculate with minimal and precise CSS rules*.
The runtime lifecycle of a Master CSS class
The runtime engine uses the standard [Web APIs - Mutation Observer](https://developer.mozilla.org/zh-TW/docs/Web/API/MutationObserver) to observe DOM class changes at runtime. It keeps active DOM usage, generated rule cache, and retained mutation rules as separate states so the browser does not need to delete and recreate CSS rules during every interaction. It is packaged as [`@master/css-runtime`](https://www.npmjs.com/package/@master/css-runtime). Most applications start it through a framework integration or a bundler entry: ```ts name=src/main.ts import CSSRuntime from '@master/css-runtime' import manifest from 'virtual:master-css-manifest' import emittedGlobals from 'virtual:master-css-emitted-globals' CSSRuntime.create({ manifest, emittedGlobals }).observe() ``` Direct browser delivery is also possible when a page is not bundled, but it is not the only runtime path: ```html ``` The following continuous DOM manipulation takes you to understand the behavior of the CSS runtime when the browser is running: #### Insert an element with a Master CSS class name into the DOM ```js const h1 = document.createElement('h1') // @MARK text-center h1.className = 'text-center' ``` A new node `html

` is inserted into the DOM tree: ```html

Hello World

``` The runtime engine observes a new node with the class `text-center` and ensures the corresponding CSS rule: ```css .text\:center { /* [!code ++] */ text-align: center /* [!code ++] */ } /* [!code ++] */ ``` #### Added Master CSS class names to elements in links ```js // @MARK font:6xl h1.classList.add('font:6xl') ``` Add class name `font:6xl` to `html

` ```html

Hello World

``` The runtime engine observes that `html

` adds the new class name `font:6xl` and ensures the corresponding CSS rule: ```css .font\:6xl { /* [!code ++] */ font-size: 3rem /* [!code ++] */ } /* [!code ++] */ .text\:center { text-align: center } ``` #### Remove the Master CSS class name from the connected element ```js // @MARK text-center h1.classList.remove('text-center') ``` Remove class name `text-center` from `html

` ```html

Hello World

``` The runtime engine observes that the class name `text-center` is removed from `html

` and updates active usage immediately. Mutation-driven cleanup may retain the generated rule briefly so a fast remove/re-add does not churn the browser CSSOM. After retained-rule cleanup, the unused rule can be deleted: ```css .font\:6xl { font-size: 3rem } .text\:center { /* [!code --] */ text-align: center /* [!code --] */ } /* [!code --] */ ``` #### Removes an element with a Master CSS class from the DOM ```js h1.remove() ``` Remove the `html

` with class `font:6xl` ```html

Hello World

``` The runtime engine observes that the `html

` element with the class name `font:6xl` is removed and updates active usage immediately. If no connected element still uses `font:6xl`, the generated rule can be retained until idle cleanup or an explicit forced cleanup removes it: ```css .font\:6xl { /* [!code --] */ font-size: 3rem /* [!code --] */ } /* [!code --] */ ``` #### All active DOM class counts have been removed At this point the DOM no longer uses those Master CSS classes. Runtime CSSOM cleanup is allowed to happen later for MutationObserver-driven removals, while direct `deleteClassRules(...)` calls still remove rules synchronously. Due to its runtime execution nature, you can modify the class name directly in the browser by inspecting the element and seeing its changes. ### Running style sheet Where are the generated CSS rules inserted? The runtime engine appends `html ``` It uses the `.insertRule()` and `.deleteRule()` methods of [Web APIs - CSSStyleSheet](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet) to manipulate native CSS rules. The text content of `style#master-css` is not a reliable live view after the runtime starts; inspect the stylesheet object when you need to see the current CSSOM. Still, you can detect the CSS rules in the current style sheet like this: ```js const sheet = document.querySelector('style[id="master-css"]').sheet console.log(sheet.cssRules) ``` When runtime code needs project tokens, modes, or component definitions, load the compiled runtime inputs from the integration. `virtual:master-css-manifest` resolves the canonical project-level manifest discovered from the CSS entry, and `virtual:master-css-emitted-globals` records variables and keyframes that the entry already emitted. ```js import CSSRuntime from '@master/css-runtime' import manifest from 'virtual:master-css-manifest' import emittedGlobals from 'virtual:master-css-emitted-globals' CSSRuntime.create({ manifest, emittedGlobals }).observe() ``` The manifest tells the runtime how to interpret project-specific tokens, modes, components, utilities, and variants. The `emittedGlobals` object is narrower: it only records variables and keyframes that the build already emitted from the CSS entry output. Dynamic classes can still be generated later, but shared global CSS is not duplicated when those classes reference an already-loaded variable or animation. ### Runtime state Runtime rendering separates the question "is this class currently used by the DOM?" from "does the runtime already have generated CSS for this class?" | State | Meaning | | --- | --- | | `classCounts` | Active connected DOM usage. It updates immediately when observed elements are added, removed, or change class names. | | `classUtilities` | Generated rule cache. It can include rules that are active, warmed, hydrated, or retained for reuse. | | `retainedClassNames` | Mutation-generated rules that are no longer used by the DOM but are intentionally kept for idle cleanup or fast reuse. | Direct runtime APIs are rule APIs, not DOM usage APIs. `ensureClassRules(...classNames)` synchronously generates or reuses rules and is the explicit warming path before inserting a large dynamic view. `deleteClassRules(...classNames)` synchronously removes generated rules and bypasses retention. The MutationObserver path is more conservative: removed DOM classes leave `classCounts` immediately, then their generated rules can be retained and cleaned later outside the interaction window. ### Interaction-heavy screens Runtime and progressive rendering work best when the classes used during interaction are already generated, hydrated, retained, or warmed. A large interaction that inserts many elements with first-time class names still asks the browser to process DOM changes and new CSS rules in the same frame window. For highly interactive UI such as editors, builders, data grids, virtualized lists, drag surfaces, or dashboards with many per-item values, prefer a mixed strategy: - Keep stable layout, typography, state, and component classes in Master CSS. - Warm predictable runtime classes with `ensureClassRules(...)` before inserting a large dynamic view. - Use inline styles or CSS variables for volatile per-element values such as coordinates, dimensions, transforms, or user-generated colors. - Use top-level native CSS or component-authored CSS for large repeated interaction states that are easier to model as selectors than as many runtime-generated utilities. This does not change class syntax or cascade semantics. It is a delivery choice: avoid making the browser generate a large number of new utility rules during the same user interaction that mutates a large DOM subtree. ### Project manifest delivery `virtual:master-css-manifest` is the project-level runtime input. It represents the compiled CSS entry graph, so it can include project tokens, modes, component definitions, utility definitions, variants, and managed keyframes. During development, integrations can serve that manifest as an inline virtual module. In production runtime builds, official integrations may emit it as a hashed JSON asset and make the virtual module import that asset before the runtime starts. Runtime-only pages need this JSON before they can interpret classes, so integrations that inject the runtime can also add: ```html ``` This does not change generated CSS or cascade order. It only moves discovery of the project manifest earlier so the runtime's later import can reuse the browser's preloaded module. --- ## Progressive Rendering Master CSS Progressive Rendering works by pre-rendering page CSS on the server or during a static build and injecting it into the page HTML. On the client, the [CSS runtime](#runtime-rendering) hydrates these rules into a virtual stylesheet, initializing a lifecycle-aware system that can respond to class name changes in real time. Progressive hydration depends on two pieces of data: `style#master-css` contains the pre-rendered CSS that can paint the first screen, and the page hydration manifest describes the generated rules that style block contains.
Server-side pre-rendering and client-side hydration process
Static and pre-rendered outputs use an external page hydration manifest by default: ```html ``` The `/_master-css/hydration/` path above is the integration-neutral route. Framework adapters can place the same artifact under their own static asset namespace. In Next.js, `@master/css.next` uses: ```html ``` This keeps the first-render CSS in the HTML while moving the runtime handoff data into a cacheable route-level JSON file. The browser can paint from `style#master-css` without waiting for the manifest request. When the runtime starts, it imports the manifest as a JSON module, adopts the existing native CSS rules, and continues observing dynamic classes. If the manifest is missing, invalid, fails to import, or no longer matches `style#master-css`, the runtime safely rebuilds the stylesheet from connected DOM classes. After adoption, progressive rendering uses the same runtime state model as runtime rendering. Hydrated rules become runtime-managed rule objects, new classes can be generated later, and mutation-driven removals can enter the retained-rule cache before idle cleanup. This keeps the first paint deterministic while still avoiding repeated CSSOM insertion/deletion during interactive updates. Inline `script#master-css-hydration-manifest` is still supported for compatibility and for dynamic SSR responses that cannot write a stable public JSON asset. Pages with no generated rules do not need a hydration manifest pointer. Do not preload the page hydration manifest. It is different from the runtime project manifest: the browser already has the CSS needed for first paint in `style#master-css`, and the hydration manifest only tells the runtime how to adopt those existing rules. ### Pre-rendering — SSG, SSR For example, the following HTML: ```html name="index.html"

Hello World

``` Render the HTML: ```ts name=server.ts import { readFileSync } from 'node:fs' import { render } from '@master/css-server' import manifest from 'virtual:master-css-manifest' const indexHTML = readFileSync('./index.html', 'utf-8') const { html, hydrationManifest } = render(indexHTML, manifest, { hydrationManifest: { type: 'external', src: '/_master-css/hydration/master-css-hydration..json' } }) ``` The server renderer parses the HTML and generates the internal style sheet plus a page hydration manifest. Official static and pre-render integrations write `hydrationManifest` to a hashed JSON asset and attach the URL to `style#master-css`: ```html

Hello World

``` What benefits does this bring? The server renderer generates the initial page CSS (**5kB**) based on the class names used in the HTML, instead of the entire application source code (**500kB**). This approach allows for a **minimal, deterministic CSS text** that is injected into the HTML, enabling fast page loads and minimal CSS output. Externalizing the hydration manifest does not make first paint faster by itself; the first paint still comes from the inline `style#master-css`. It reduces HTML transfer and parse pressure as the number of generated rules grows, and lets the route-level handoff data be cached separately. ### CSS hydration Master CSS hydration is the process that restores the server-side or build-time rendered CSS on the client. This includes reusing the pre-rendered CSS structures, persisting the application CSS state, and reconstructing the style sheet into virtual memory.
Master CSS Hydration — Creates virtual rules from DOM style sheet
The runtime reads explicit `hydrationManifest` options first. Without an explicit option, `CSSRuntime.create()` reads inline `script#master-css-hydration-manifest` for compatibility. When `runtime.needsHydrationManifest()` is true, call `await runtime.loadHydrationManifest()` before `runtime.observe()` to import the URL from `style#master-css[data-master-css-hydration-manifest]`. Each manifest rule stores the class name, layer, priority, selector text, generated CSS text, and any referenced variables or animations. During hydration, the runtime compares that IR with the native rules already present in `style#master-css`. When they match, it attaches those native CSS rules to runtime-managed rule objects instead of regenerating them. Once hydrated, Master CSS can efficiently detect new or removed class names and update styles accordingly, without needing to reparse or regenerate previously defined rules. Classes that were not present in the initial HTML are still generated at runtime. Classes removed after hydration leave `classCounts` immediately; their generated rules may be retained briefly and removed later by idle cleanup or by an explicit `flushRetainedClassRules()` call. The [CSS runtime](#runtime-rendering) then takes over to detect any changes in dynamic class names. This page hydration manifest is different from the project manifest and `emittedGlobals`. The project manifest tells the runtime how to interpret tokens, modes, components, utilities, and variants. `emittedGlobals` records variables and keyframes that the CSS entry already emitted. The page hydration manifest only describes the CSS rules that were generated into one rendered page. --- ## Static Rendering Static rendering is a zero-runtime rendering mode where the build scans source files, finds complete Master CSS class strings, validates them with the active engine manifest, and writes the resulting CSS before deployment. The source scanner does not observe the DOM and does not execute application code. Its input is source text, CSS entries, scanner options, and the compiled project manifest. Its output is a CSS asset that the browser loads like any other stylesheet. The CSS entry point is explicit: import `@master/css` from the stylesheet that should receive generated Master CSS. In static mode, integrations replace that import with generated CSS and treat the same stylesheet as a native CSS pruning root. #### Load the scanning context The integration creates a source scanner with its default source discovery, optional source directives, optional fixed classes, and the project CSS entry graph. During development, integrations use their host watch, HMR, or invalidation system to reset or update this context. ```css name=index.css @import '@master/css'; ``` Add `@source` only when this stylesheet must include source outside the integration's normal scan path or define a scoped native CSS pruning root. #### Scan source text Source files such as `.html`, `.js`, `.jsx`, `.ts`, `.tsx`, `.vue`, `.svelte`, `.astro`, `.md`, and `.mdx` are scanned as text. The scanner collects candidate class strings from markup and string literals, then filters obvious non-class tokens before validation. ```html name=src/index.html ``` #### Validate candidates Each candidate is passed through the Master CSS engine. Valid classes insert rules into the same layers used by runtime and server rendering; invalid candidates are cached and skipped on later scans. ```css name=index.css @components { btn { @compose inline-flex px:md; } } ``` With this project manifest, `btn` is valid because the project defines it, and `text-center` is valid because it is a built-in utility. Manifest-defined classes are still on-demand: defining `btn` does not emit anything until `btn` appears in scanned source or in the scanner's fixed class list. #### Compose final CSS The generated stylesheet contains the valid Master CSS rules, retained native CSS from managed style entries, and any referenced variables or keyframes needed by those rules. ```css name=generated.css @layer components { .btn { display: inline-flex; padding-left: 1rem; padding-right: 1rem; } } @layer utilities { .text\:center { text-align: center; } } ``` ### Generated stylesheet entry In static mode, import the generated stylesheet from the stylesheet your framework already bundles. ```css name=src/style.css @import '@master/css'; ``` Use one `@import '@master/css'` entry for each generated stylesheet root. That import is also the insertion point for generated Master CSS, default base styles, theme variables, and utilities required by detected classes. `@import '@master/css'` may be placed anywhere inside the top-level CSS import block. Ordinary CSS imports in that block are still emitted before generated Master CSS; keep the Master CSS import before normal style rules. ### Native CSS entries Regular CSS outside Master CSS directives remains native CSS. When a stylesheet imports `@master/css`, integrations treat that stylesheet as a pruning root by default and prune class selectors against detected source classes. Those native rules can also pull matching theme variables referenced by `var(--*)` and managed `@theme` keyframes referenced by animation declarations. Add `@preserve native;` when native CSS must be preserved. ```css name=src/style.css @import '@master/css'; .native-card { border: 1px solid rgb(0 0 0 / 12%); } .unused-card { color: red; } ``` ```html
Card
``` The generated CSS contains `.native-card` and `.btn` when both classes are scanned. `.unused-card` is removed because no scanned source uses it. ### Dynamic class limitations Static rendering depends on complete class strings that exist in scanned source files. It cannot evaluate conditions, run helper functions, resolve remote content, or predict classes assembled by string concatenation. (x) Do not construct partial class names. ```tsx const className = 'bg:' + (error ? 'red': 'green') ``` (o) Map states to complete class names. ```tsx const className = error ? 'bg:red' : 'bg:green' ``` (o) Pass dynamic values through CSS variables while keeping the class static. ```tsx
``` For the full source scanning model, see [Scanning latent classes](/guide/scanning-latent-classes). For native CSS pruning, see [Native CSS pruning](/guide/native-css-pruning). --- ## Shared rendering pipeline Rendering modes change delivery, not the authoring model. The source of truth is the project CSS entry graph. A stylesheet becomes part of that graph when it contains a top-level `@master entry;` marker or imports `@master/css`. Use `@master entry;` when the file only needs to declare manifest input, and use `@import '@master/css'` when the stylesheet should also receive generated CSS in static builds. ```css name=index.css @import '@master/css'; @settings { root-size: 16; } @theme { --color-primary: #4f46e5; --breakpoint-md: 48rem; @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } } @custom-variant motion-safe { @media (prefers-reduced-motion: no-preference) { @slot; } } @components { btn { @compose inline-flex items-center px:md py:xs r:md; background: var(--color-primary); } } ``` These CSS-first directives are manifest inputs. The compiler lowers tokens, managed keyframes, settings, variants, components, utilities, and native composed rules into a `MasterCSSManifest`. Runtime rendering, static rendering, server rendering, language tooling, linting, and framework integrations all consume that same IR, so class syntax and cascade behavior stay consistent even when CSS is delivered differently. | Artifact | Produced by | Used by | Purpose | | --- | --- | --- | --- | | CSS entry graph | Project stylesheets with `@import '@master/css'` or the lightweight `@master entry;` marker | Compiler, integrations, static renderer | Authoring source for tokens, settings, variants, managed styles, source directives, and native CSS roots. | | `MasterCSSManifest` | `@master/css-compiler` and `@master/css-project` | Engine, runtime, server renderer, scanner, linting, language tooling | Shared IR that describes how class names become sorted CSS rules. | | `virtual:master-css-manifest` | Official build integrations | Application runtime code and framework integrations | ESM module for the canonical project-level manifest discovered from the CSS entry graph. In production runtime builds, this module may import an emitted project manifest JSON asset. | | Project manifest JSON asset | Official runtime integrations | `virtual:master-css-manifest` facade and the runtime | Cacheable JSON form of the project manifest. Pure runtime pages can preload it because the runtime needs it before interpreting project classes. | | `virtual:master-css-emitted-globals` | Static and build integrations | Runtime code | Counts variables and keyframes already emitted by the CSS entry output, so runtime rendering does not insert duplicate global CSS. | | Hydration manifest | Server rendering and progressive integrations | Runtime hydration | JSON rule IR with `version: 1`, used to map `style#master-css` back into runtime-managed rule objects. | | Next build manifest | `@master/css.next` when `manifest` is enabled | Build analysis and reporting | Route/output report for rendered files; it is separate from the runtime hydration manifest. | --- ## Comparisons This section provides a detailed comparison of different rendering modes. Each mode is evaluated based on various criteria such as application scenarios, performance, and generated source. --- # Responsive Design Source: https://rc.css.master.co/en/guide/responsive-design Summary: Adapt your user interface to different devices with flexible responsive syntax. ## Overview ```html
…
``` Master CSS allows for the conditional application of styles at different viewport and container sizes. Viewport queries use [breakpoint tokens](/guide/breakpoints), while container queries use [container size tokens](/guide/containers). --- ## Based on viewport breakpoints CSS Media Queries allow styles to be applied based on the *size of the viewport* rather than individual *elements*. This makes it possible to create responsive layouts that adapt to different viewport widths—such as mobile phones, tablets, and desktops—by defining breakpoints at specific widths. These breakpoints enable developers to change layouts, typography, spacing, and more to ensure an optimal user experience across devices. ### Using responsive breakpoints The syntax is `@`, where `` can be any [breakpoint theme token](/guide/breakpoints), such as `xs`, `sm`, `md`, `lg`, etc. ```html
…
``` ### Querying viewport ranges Use [comparison](/guide/conditional-queries#comparison-operators) and [logical](/guide/conditional-queries#logical-operators) operators to create more complex viewport range queries. ```html
…
``` ### Creating responsive wrappers Set fixed maximum widths from the container scale when a wrapper should step through product layout widths. ```html
…
``` --- ## Based on container sizes CSS [Container Queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_containment/Container_queries) allow styles to be applied based on the *size of a container*, rather than the size of the *viewport*. This makes it easier to build responsive components that adapt to their parent containers. ### Using container queries The `container` class is a utility class that applies the `container-type: inline-size;` to the element, making it a `@container()` for container queries. (resize) Try making the container smaller. ```html
…
``` Container queries use the [container scale](/guide/containers), which can use different values from viewport breakpoints. ### Querying container ranges Use [comparison](/guide/conditional-queries#comparison-operators) and [logical](/guide/conditional-queries#logical-operators) operators to create more complex container range queries. ```html
…
``` ### Creating named containers Use the `container:/` to create a named container with a specific type, and then use the `@container()` query to apply styles based on the size of a named container. ```html
``` --- ## Strategies When it comes to designing and developing responsive web pages, [mobile-first](#mobile-first) and [desktop-first](#desktop-first) are two common development strategies. The decision between these two strategies depends on your project requirements, target audience, and operational decisions. Also, we propose another flexible strategy - [Syntax-first](#syntax-first). ### Mobile-first The mobile-first strategy is a design and development approach that initially focuses on designing and optimizing for smaller viewports, such as mobile phones and tablets, and then gradually expanding to larger viewports, including desktop computers. For example, your company is launching a game primarily targeting mobile users with potential future releases for desktop users based on market response; adopting a mobile-first strategy would be ideal at this stage. (i) In mobile-first, **styles not bound by viewports are considered to define the mobile UI.** ```html

``` Gradually adjust the UI for larger viewports. (wand) Increase the font size to `32/16rem` when the viewport width is larger than `1024/16rem`. ```html

``` - Paragraph font size is `24/16rem` in viewport `<1024/16rem` - Paragraph font size is `32/16rem` in viewport `>=1024/16rem` This relies on CSS precedence behavior to override mobile styles with new styles on larger viewports. ### Desktop-first On the other hand, the Desktop-first development strategy initially prioritizes designing and optimizing for larger viewports, such as desktop computers, and then gradually scaling down to smaller viewports, like mobile phones and tablets. For example, your company is launching a web drawing software primarily targeting designers with potential future releases for mobile users based on market response; adopting a desktop-first strategy would be ideal at this stage. (i) In desktop-first, **styles not bound by viewports are considered to define the desktop UI.** ```html

``` Gradually adjust the UI for smaller viewports. (wand) Decrease the font size to `24/16rem` when the viewport width is less than `1024/16rem`. ```html

``` - Paragraph font size is `24/16rem` in viewport `<1024/16rem` - Paragraph font size is `32/16rem` in viewport `>=1024/16rem` This relies on CSS precedence behavior to override mobile styles with new styles on larger viewports. ### Syntax-first Thanks to the syntactic flexibility of Master CSS, free yourself from the constraints of mobile-first or desktop-first, which not only gives you a better development experience but also makes you have less markup and less CSS output. For example, set the background to white only on mobile. (!) With mobile-first, it's necessary to revert to the original background on larger viewports. ```html

``` (o) Add `mcss @ ``` For example, set the background to white only on the desktop. (!) With desktop-first, it's necessary to revert to the original background on smaller viewports. ```html
``` (o) Add `mcss @md` directly to restrict to large viewports. ```html
``` You don't need to waste energy sticking to a specific development strategy; use the most direct way to solve the current responsive layout. --- # Route-level Styles Source: https://rc.css.master.co/en/guide/route-level-styles Summary: Write route, page, and component-specific CSS with @reference, native selectors, @compose, variants, container queries, and native keyframes. ## Overview Route-level styles are ordinary CSS files loaded by one route, page, view, or component. They can use Master CSS as compile-time context without becoming a global entry. Reference the app stylesheet at the top of the local file: ```txt app/ globals.css home/ page.tsx home.css ``` ```css name=app/home/home.css @reference "../globals.css"; ``` Then write native CSS selectors. Use `@compose` when Master CSS classes are clearer than hand-written declarations. ```css name=app/home/home.css @reference "../globals.css"; .home-section { @compose py:5xl; } ``` Load the route stylesheet from the route, page module, or component entry that owns it: ```ts name=app/home/page.tsx import "./home.css" ``` The global stylesheet still has to be loaded by the app. `@reference` gives the route stylesheet compile-time access to project tokens, variants, and shared class vocabulary; it does not import the app CSS output again. --- ## Reference the app entry Use `@reference` when a route stylesheet needs project context but should ship as its own CSS output. ```css name=app/home/home.css @reference "../globals.css"; .pricing-hero { @compose grid gap:lg py:5xl; } .pricing-card { @compose p:lg b:1px|solid|base r:xl surface:raised; } ``` The referenced file is context-only. Native CSS from the referenced stylesheet is not copied into the route stylesheet. The route output contains only the lowered route rules plus any theme variables or managed keyframes the route actually needs and the global entry has not already emitted. This keeps route CSS chunks self-contained without duplicating the global stylesheet. --- ## Write native selectors Route styles do not need on-demand generation. Treat route classes like traditional CSS that belongs to that route. ```css name=app/home/home.css @reference "../globals.css"; @layer components { .home-bento { @compose grid gap:md; grid-template-columns: minmax(0, 1fr); } .home-bento-card { @compose p:lg b:1px|solid|base r:xl surface:raised; } } ``` Use classes when the selector is part of the page structure. Use native selectors when they are clearer: ```css name=app/home/home.css .home-bento-card > h2 { @compose text:lg font:medium; margin-block: 0 0.5rem; } .home-bento-card > p { @compose leading:lg text:muted; margin: 0; } ``` Because these are native rules, they are emitted with the stylesheet that imports them. If a selector becomes reused across multiple pages, move the shared role to [Global styles](/guide/global-styles#shared-vocabulary). --- ## Use variants locally Use rule-local variants for route states, breakpoints, and modes without moving the selector into global vocabulary. ```css name=app/home/home.css @reference "../globals.css"; .home-cta { @compose inline-flex items-center justify-center gap:xs h:12x px:lg r:xl bg:blue fg:white; @variant dark { @compose bg:blue-60; } @variant = 42rem) { .home-feature-list { grid-template-columns: repeat(3, minmax(0, 1fr)); } } ``` Use viewport breakpoints when the layout depends on the page viewport. Use container queries when the section can appear inside different shells, sidebars, or slots. --- ## Promote shared patterns Keep route CSS local while the structure belongs to one route. Promote only the stable part: - Move repeated values into [Theme Tokens](/guide/theme). - Move repeated UI roles into [Global styles](/guide/global-styles#component-classes). - Move repeated low-level styling capabilities into [Global styles](/guide/global-styles#custom-utilities). - Keep unique layout, content structure, and route-only animation in the route stylesheet. This keeps global CSS small, route CSS explicit, and shared vocabulary intentional. --- # Scanning latent classes Source: https://rc.css.master.co/en/guide/scanning-latent-classes Summary: Understand how Master CSS finds possible class names in source files and turns visible usage into generated CSS. ## Overview Static rendering starts by finding latent classes. A latent class is a possible class name found in source text before Master CSS has proved whether it is a valid utility, project-defined class, or native class from a pruned stylesheet. ```txt source text -> latent class candidates -> validated classes -> generated CSS ``` The scanner does not run your app. It reads files as text, collects strings that may be classes, and lets the Master CSS engine decide which candidates can produce CSS. ```html name=src/index.html

Release notes

``` The source contains `card`, `p:md`, `bg:white`, `shadow:md`, `font:lg`, and `font:semibold`. Those candidates are validated against the active manifest. Valid classes generate CSS; invalid candidates are cached and ignored. ```css name=generated.css @layer utilities { .p\:md { padding: 1rem } .shadow\:md { box-shadow: var(--shadow-md) } } ``` The same scanning model is used by build integrations and by tools that call `@master/css-scanner` directly. --- ## Source boundaries Build integrations and CLI flows scan common source-like project files by default. Ordinary app files such as HTML, JavaScript, TypeScript, JSX, TSX, framework files, Markdown, MDX, and PHP should not need a broad `@source` directive or a matching test-file exclusion. Use `@source` and `@source not` only when a stylesheet needs an explicit exception, such as content outside the normal project scan, shared workspace source, or a scoped native CSS pruning root. ```css name=index.css @import '@master/css'; @source '../content/**/*.mdx'; @source '../packages/ui/**/*.{ts,tsx}'; @source not '../packages/ui/**/*.stories.tsx'; ``` `@source` adds files that may contain classes. `@source not` removes files from that explicit source set. Multiple source directives are combined as `(source union) - (source not union)`. For exact stylesheet directive syntax, see [CSS directives](/guide/directives). In Vite, transformed modules are also fed to the scanner during development. That makes updates fast, but production correctness still depends on class names that exist in scanned source files or are explicitly included. --- ## Candidate scanning Scanning is intentionally broad. The scanner looks through markup, JSX, strings, template literals, object maps, and framework files for tokens that could be class names. ```tsx name=src/Button.tsx const toneClasses = { neutral: 'bg:white text:neutral', destructive: 'bg:red-60 fg:white' } export function Button({ destructive }: { destructive?: boolean }) { return ( ) } ``` The scanner can see all complete class strings in this file: ```txt bg:white text:neutral bg:red-60 fg:white btn r:md px:md ``` It will also see unrelated words from source text. That is expected. Candidates only matter after validation. ```tsx name=src/EmptyState.tsx export function EmptyState() { return

No invoices found.

} ``` Words such as `function`, `return`, `No`, `invoices`, and `found` may be discovered as candidates, but they do not match valid Master CSS rules or known native classes, so they do not produce output. --- ## Validation After candidate scanning, Master CSS validates each class against the active manifest. A candidate can be accepted in three common ways: - It is a built-in utility, such as `block`, `fg:red-60`, or `grid-cols:3`. - It is defined by your project CSS entry and compiled into the manifest. - It matches a native class collected from a stylesheet that imports [`@master/css`](/guide/native-css-pruning). ```css name=index.css @components { btn { @compose inline-flex items-center h:40px px:md r:md; } hero-title { @compose m:0 font:5xl font:heavy text:neutral; } } ``` ```tsx name=src/Hero.tsx export function Hero() { return (

Master CSS

Read docs
) } ``` `hero-title` and `btn` are valid because the project CSS entry defines them. `grid`, `gap:xl`, `bg:blue-60`, and `fg:white` are validated through the utility engine. Configured classes are still on-demand. Defining `.btn` in the project CSS entry does not emit it by itself; `.btn` must appear in scanned source or be included through `@safelist`. --- ## Complete classes Static rendering works when the complete class string exists in source. It cannot infer class names from fragments, data returned by an API, or values assembled after startup. (x) Do not build class names from fragments. ```tsx const className = 'bg:' + (error ? 'red-60' : 'green-60') ``` The complete strings `bg:red-60` and `bg:green-60` do not exist in source, so static rendering cannot reliably generate either rule. (o) Write complete class names. ```tsx const className = error ? 'bg:red-60' : 'bg:green-60' ``` For component variants, map dynamic inputs to complete class lists. (x) Avoid utility fragments in props. ```tsx function Badge({ tone }: { tone: 'red' | 'green' | 'gray' }) { return Status } ``` (o) Use a static variant map. ```tsx const toneClasses = { destructive: 'bg:red-60 fg:white', confirmed: 'bg:green-60 fg:white', neutral: 'bg:gray-10 fg:gray-90' } function Badge({ tone }: { tone: keyof typeof toneClasses }) { return Status } ``` This also gives each variant room to choose its own contrast, hover state, disabled treatment, and dark-mode behavior. --- ## Runtime values When the value is dynamic but the declaration shape is stable, keep the class static and pass the value through a CSS variable. ```tsx function Headline({ size }: { size: string }) { return (

Launch notes

) } ``` The class `font-size:$headline-size` is complete and visible to the scanner. The runtime value lives in `--headline-size`, which is normal CSS. Use the same pattern for data-driven sizes, positions, and progress values. ```tsx function Progress({ value }: { value: number }) { return (
) } ``` If the class name itself only exists after the page is running, use [runtime rendering](/guide/rendering-modes#runtime-rendering) or [progressive rendering](/guide/rendering-modes#progressive-rendering). The browser runtime can observe the DOM and generate rules for classes that appear later. --- ## Included and excluded classes Use `@safelist` for bounded classes that do not exist in scanned source. Common cases include CMS enums, database values, server-rendered fragments, or a third-party widget with a known class contract. ```css name=index.css @import '@master/css'; @safelist 'opacity:1 transform:translateY(-5px):hover bg:blue-60@dark'; ``` `@safelist` does not bypass validation. The class still needs to be a valid Master CSS class, a project-defined class from the compiled manifest, or a known native class from a pruned stylesheet. Use `@blocklist` when broad scanning finds tokens that look like valid classes but should not generate CSS. ```css name=index.css @import '@master/css'; @blocklist 'debug-*'; @blocklist 'example-token'; ``` Keep both lists small. The most reliable scanning path is still complete class strings in source. --- ## Checklist - Put complete class names in scanned source. - Map variants to complete class strings. - Use CSS variables for runtime values. - Rely on integration or CLI defaults for ordinary app source files. - Add `@source` only for extra source roots or scoped pruning roots. - Use `@safelist` only for bounded classes the scanner cannot see. - Use `@blocklist` for real false positives. - Use runtime or progressive rendering for classes created after startup. - Import [`@master/css`](/guide/native-css-pruning) from stylesheet roots whose native CSS class rules should be pruned by usage. --- # Sizing Source: https://rc.css.master.co/en/guide/sizing Summary: Choose fluid dimensions, measured sizes, container caps, constraints, and responsive sizing rules for stable layouts. ## Overview Sizing describes the space an element should claim, the limits it should respect, and the boundary where that decision changes. In CSS this includes [width](https://developer.mozilla.org/en-US/docs/Web/CSS/width), [height](https://developer.mozilla.org/en-US/docs/Web/CSS/height), min and max constraints, intrinsic keywords, percentages, viewport units, container values, and CSS functions. Master CSS keeps sizing decisions close to the element that owns them. Use `w:*` and `h:*` for one axis, `size:*` when both axes intentionally match, `min-*` and `max-*` for constraints, container tokens for shared layout surfaces, and responsive variants when the size changes by viewport or container. Fluid wrapper Measured object --- ## Choose a sizing role A sizing class should have one clear job. It can set the preferred size, keep an element from collapsing, cap growth, tie both axes together, or move the decision to a responsive boundary. Use one-axis rules when the element is rectangular by role. Use `size:*`, `min:*`, or `max:*` only when both axes genuinely share the same decision. ```html
...
``` --- ## Start fluid, then constrain Most layout should fill the space it receives and then stop at a cap. A fluid wrapper with `w:full max-w:*` behaves better across viewports than one fixed width that only fits one screen. ```html
...
...
``` Use `w:full` when the element should follow its parent, percentages such as `w:50%` for proportional regions, `max-w:*` for caps, and CSS functions such as `clamp()` when the bound itself should be fluid. ```html
...
``` Percentage widths and heights follow native CSS behavior. The parent needs a definite height before `h:full` or `h:50%` can resolve predictably. --- ## Use container tokens Sizing utilities read the `container` namespace contextually. `w:md`, `max-w:5xl`, `size:sm`, `min-w:xs`, and `flex-basis:lg` use `--container-*` tokens without repeating the namespace in markup. ```html
...
``` Use container tokens for shared layout surfaces: page wrappers, panels, modals, sidebars, drawer widths, and component caps. Use local `ch`, `x`, or CSS functions when the dimension belongs to content measure or one component's private geometry. For the full container namespace and query model, see [containers](/guide/containers#namespace-for-container-values). --- ## Use measured sizes The `x` suffix multiplies the [base unit](/guide/variables-and-modes#project-settings), which defaults to **4 pixels**. For example, `1x` is `0.25rem`, `4x` is `1rem`, and `10x` is `2.5rem`. Use `x` values for measured component geometry such as icons, avatars, handles, skeleton blocks, and fixed media slots. For page structure, reach for `w:full`, percentages, container tokens, viewport units, text units, or `clamp()` first. ```html
...
``` --- ## Pair axes deliberately `size:*` is not a shorter way to avoid thinking about dimensions. It is the right tool when an element is square by design. size:14x w:full h:14x ```html
...
``` When an element should keep a non-square ratio, use [aspect ratio](/reference/aspect-ratio) with a width instead of locking both dimensions. ```html ``` --- ## Constrain instead of forcing Min and max rules are often more stable than fixed widths. They let content, containers, and responsive variants negotiate space without overflow. min-w:0 max-w:96x ```html
Long content...
``` In flex and grid layouts, `min-w:0` is the common fix for text or media that refuses to shrink. Without it, intrinsic content can force a row wider than its container even when the parent has a max width. Use `min-h:*` for baseline regions that may grow, such as app shells, empty states, and hero sections. Use `max-h:*` for scrollable panels, menus, and media regions that must stay inside the viewport. --- ## Adapt at the right boundary Sizing classes can use the same [breakpoints](/guide/breakpoints), [containers](/guide/containers), selectors, and media queries as other utilities. Choose the boundary that owns the decision. ```html
...
``` Use viewport breakpoints when the whole page shell changes. Use container queries when a reusable component should adapt to the space it receives in a sidebar, modal, card grid, or main content column. --- ## Customize sizing tokens When a dimension becomes part of the product language, add a named container variable in the project CSS entry. Use explicit CSS lengths for fixed values; functions are preserved. ```css name=index.css @theme { --container-sidebar: 17.5rem; --container-measure: 72ch; --container-panel: clamp(18rem, 50vw, 42rem); } ``` ```html
...
...
``` Use descriptive names such as `sidebar`, `measure`, `panel`, or `media` instead of numeric keys. Numeric keys are easy to confuse with raw values such as `w:1px` or `w:2px`. --- ## Avoid brittle sizing (x) A page wrapper is fixed, so small screens overflow. ```html
...
``` (o) The wrapper fills available space and stops at a shared cap. ```html
...
``` (x) A square component repeats separate width and height values that can drift. ```html ``` (o) The component uses one sizing decision. ```html ``` (x) A flex child has a max width, but its content can still force overflow. ```html
Long unbroken content...
``` (o) The flexible child is allowed to shrink. ```html
Long unbroken content...
``` --- # Spacing Source: https://rc.css.master.co/en/guide/spacing Summary: Use spacing tokens, base-unit multipliers, and precise low-level values for layout rhythm. ## Overview Spacing controls the rhythm inside components, between related elements, and across page sections. Master CSS maps the default spacing scale to `spacing` variables, so padding, margin, gap, and inset can share the same design language. Use the scale by relationship: * `4xs` to `2xs` for micro spacing between icons, tags, compact controls, and inline text. * `xs` to `sm` for form fields, list rows, toolbar controls, and tight component groups. * `md` as the default component rhythm. * `lg` to `xl` for card padding, grouped content, and larger component separation. * `2xl` to `5xl` for layout gutters, section spacing, and large editorial rhythm. ```html
1
2
...
``` --- ## Namespace for spacing The `spacing` variable namespace is shared across padding, margin, gap, inset, scroll spacing, and similar layout rules. This lets spacing-related utilities use `md`, `lg`, or project token names without the `spacing-` prefix. ```css name=index.css @theme { --spacing-sm: 0.75rem; --spacing-md: 1rem; --spacing-lg: 1.5rem; --spacing-wide: 6rem; } ``` Apply the custom spacing tokens in your markup: ```html
...
``` --- ## Using spacing multiplier The `x` suffix multiplies the [base unit](/guide/variables-and-modes#project-settings) theme setting, which defaults to **4 pixels**. Use it for measured geometry that should stay aligned with the spacing grid but does not need a named token. For example, `1x` is `0.25rem`, `2x` is `0.5rem`, `3x` is `0.75rem`, and `8x` is `2rem`. ```html
``` For product surfaces, prefer named spacing tokens such as `sm`, `md`, and `lg`. Use `x` values for measured local geometry, such as icon size, avatar size, skeleton blocks, or a component-specific fixed width. --- ## Exact pixel values Use `0` for resets, explicit `1px` for hairlines, and other `px` units when a value needs exact pixel geometry. Bare numbers are emitted as written, so `p:1` becomes `padding: 1` and is not a valid CSS length. ```html
0px, margin: 0rem
1px, padding: 1px
2px, width: 0.125rem
``` (!) Avoid mixing named spacing tokens, `x` multipliers, and exact pixel values arbitrarily. Prefer named tokens for layout rhythm, `x` values for measured local geometry, and `px` values only for hairlines or exact pixel adjustments. --- ## Common mistakes ### Do not use numeric keys as tokens (x) Avoid defining spacing tokens with numeric keys. ```css name=index.css @theme { --spacing-1: 0.25rem; /* [!code --] */ --spacing-2: 0.5rem; /* [!code --] */ } ``` Numeric keys are easy to confuse with low-level CSS values. Prefer semantic token keys like `sm` or `card`, then use `p:1px` for a 1px value or `p:1x` for the default 4px base unit. (o) Use descriptive scale or role keys. ```css name=index.css @theme { --spacing-sm: 0.75rem; --spacing-compact: 1.25rem; --spacing-relaxed: 6rem; } ``` --- ## Summary Master CSS provides a unified system for defining spacing: * Use named spacing tokens for shared rhythm. * Use `x` multipliers for measured local geometry. * Use `0`, `1px`, or explicit pixel units for resets and exact pixel adjustments. * Avoid numeric token keys so markup stays clear. --- # State Selectors Source: https://rc.css.master.co/en/guide/state-selectors Summary: Learn how to append selectors for hover, focus, attributes, descendants, pseudo-elements, and custom states. ## Overview ```html
``` State selectors let one declaration apply only when a selector matches. Append the selector after the declaration value: ```txt property:value ``` Common examples include interaction states such as `:hover`, validation states such as `:invalid`, and attributes such as `[disabled]` or `[open]`. ```html

``` Selectors can be stacked when the CSS selector itself needs more detail. ```html
``` If you also need a breakpoint, mode, or other condition, put the [conditional query](/guide/conditional-queries) after the selector. ```html ``` For readability, Master CSS includes built-in selector aliases for selectors that appear often. ```html
``` Write longer project-specific selectors directly. ```html
``` --- ## Basic selectors Master CSS accepts native selector syntax. The selector is relative to the element that owns the class unless a combinator points to another element. | Selector | Description | Preview CSS | |-----------------------|-------------------------------------------------------|-------------------------------------------| | `*` | Universal selector | `css * { margin: 0; }` | | `element` | Type selector | `css p { color: red; }` | | `.class` | Class selector `css .box { padding: 1rem; }` | | `#id` | ID selector | `css #header { background: blue; }` | | `[attribute]` | Attribute selector | `css [disabled] { opacity: 0.5; }` | | `:pseudo-class` | Pseudo-class selector | `css a:hover { color: blue; }` | | `::pseudo-element` | Pseudo-element selector | `css p::first-letter { font-size: 2em; }` | ### `*` — Universal Use `*` as a wildcard. In `>*`, every direct child matches. ```html
hit
hit
...
``` ### `element` Use a type selector to target elements by tag name. ```html
hit
``` (i) If a raw type selector is hard to read or conflicts with nearby syntax, wrap it with `:is()` or `:where()`. ```html ``` ### `.class` a application as class custom for selector state, such Use `.active`, `.selected`, or `.expanded`. ```html
...
``` ### `#id` Use an ID selector when the state is tied to a unique element. ```html ``` ### `[attribute]` Use attribute selectors for DOM state that already lives in markup, such as `[disabled]`, `[open]`, `aria-*`, and `data-*`. ```html ``` ### `:pseudo-class` Use pseudo-classes for browser-managed states. ```html ``` ### `::pseudo-element` Use pseudo-elements such as `::before` and `::after` when the style should target generated content. ```html
quotes
``` --- ## Combinators Combinators target elements by their relationship to the element that owns the class. Use them when the declaration should style a child, sibling, or descendant instead of the element itself. | Selector | Description | Preview CSS | |-------------------|---------------------------|-----------------------------| | `A B` | Descendant selector (`_`) | `css nav a { color: white; }` | | `A > B` | Child selector | `css ul > li { list-style: none; }` | | `A + B` | Adjacent sibling selector | `css h1 + p { margin-top: 0; }` | | `A ~ B` | General sibling selector | `css h1 ~ p { color: gray; }` | ### `_` — Descendant Use `_` as the descendant combinator. It stands in for the CSS space, because spaces split class names in HTML. ```html
hit
hit
hit
hit
``` ### `>` — Child Use `>` when only direct children should match. ```html
hit
``` ### `+` — Adjacent sibling Use `+` to style the next sibling when it appears immediately after the current element. ```html
hit
``` ### `~` — General sibling Use `~` to style later siblings that share the same parent. ```html
hit
hit
hit
``` --- ## Selector groups Use `,` when the same declaration should apply to several selectors. ```html
quotes
``` Selector groups also work with combinators. In this example, the declaration applies to direct `div` and `span` children. ```html
hit
``` --- ## Pseudo-classes ### `:hover`, `:active`, `:focus` Use interaction pseudo-classes to give controls feedback as people hover, press, focus, or navigate with a keyboard. (click) Try clicking the button to see states change ```html ``` Use `:focus-visible` for keyboard focus rings when you want to avoid showing the focus style after every pointer click. ```html ``` ### `:first`, `:last`, `:odd`, `:even` Use structural shorthands such as `:first`, `:last`, `:odd`, and `:even` to style list items by position. Write native selectors such as `:nth-child(N)` directly when they are clearer. {furnitures.map((furniture, index) => )} ```html
  • …
``` ### `:valid`, `:invalid`, `:required` Use form validation pseudo-classes to reflect native validity without writing JavaScript state. (type) Try typing `co` as a valid email address ```html ``` ### `:disabled` Use `:disabled` for controls that cannot be interacted with. ```html ``` ### `:checked`, `:indeterminate` Use `:checked` and `:indeterminate` for checkboxes, radio buttons, switches, and custom controls backed by native inputs. ```html ``` ### `:rtl`, `:ltr` Use `:rtl` and `:ltr` to react to text direction. They map to `:dir(rtl)` and `:dir(ltr)`. ```html
...
``` ### `:has()` Use `:has()` when the current element should change because it contains a matching child or descendant. ```html
Item 1
Item 2
Item 3
``` ### `:not()` Use `:not()` to exclude a selector from the match. ```html
...
``` ### `:of()` `:of()` is the only proprietary selector introduced by Master CSS. It lets the current element respond to a parent, ancestor, or previous sibling. Use native selectors first when they can express the relationship; use `:of()` when you need to style the current element from outside-in context. (i) Style the element when an ancestor matches. ```html
hidden
``` (i) Style the element when its parent matches. ```html
hidden
``` (i) Style the element when its previous adjacent sibling matches. ```html
hidden
``` (i) Style the element when one of its preceding siblings matches. ```html
hidden
``` (x) Do not put combinators or pseudo-elements before `:of()`. ```html
hidden
``` --- ## Pseudo-elements ### `::before`, `::after` Use `::before` and `::after` to style generated content attached to the element. ```html
Be the change you wish to see in the world.
``` ### `::scrollbar` Style common scrollbar surfaces with `::scrollbar`, `::scrollbar-thumb`, and `::scrollbar-track` shorthands. Write native vendor selectors such as `::-webkit-scrollbar-corner` directly for less common parts. (hover) Try scrolling horizontally and interact with the scroll bar {animals.map((animal) => )} ```html
``` --- ## Attribute selectors ### `[open]` Use `[open]` to style a `
` element while it is expanded. ```html
Details

Details content goes here.

``` ### `[aria-=]` Use [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) attributes when accessible state is already present in the DOM. ```html
...
``` ### `[data-=]` Use `data-*` attributes for component state that is not covered by native attributes or ARIA. ```html
...
``` ### `[=]` Match an exact attribute value. ```html ``` ### `[^=]` Match values that start with a specific string. (i) Links that start with `http`. ```html External ``` ### `[$=]` Match values that end with a specific string. ```html PDF ``` ### `[*=]` Match values that contain a specific string. ```html
...
``` ### `[|=]` Match a value exactly or followed by a hyphen, which is common for language codes. ```html
...
``` ### `[~=]` Match one word inside a whitespace-separated attribute value. ```html
...
``` --- # Style Declarations Source: https://rc.css.master.co/en/guide/style-declarations Summary: Learn how Master CSS turns class names into CSS declarations, values, units, functions, variables, and shorthands. ## Overview ```html

Hello, World!

``` Master CSS classes are CSS declarations written directly in markup. Read each class from left to right: start with the style you want, then add optional [state selectors](/guide/state-selectors) and optional [conditional queries](/guide/conditional-queries). ```html ``` The examples in this guide start with explicit CSS-like declarations, then show how to shorten them with utilities, shorthands, abbreviations, variables, and explicit units. Common native properties such as spacing, sizing, radius, color, and timing can still use Master CSS tokens and multiplier units, while rare CSS properties can use valid native declaration syntax directly. When you are learning a new class, write the explicit form first. Once the output is clear, use the shorter form that still reads well to your team. --- ## Basic syntax ### Utilities ### Multi-style shorthands ### Ambiguous shorthands ### Motion longhands ### Property abbreviations ### Native declaration fallback ### Variable properties ### Group ### Important --- ## Values ### Decimal ### Negative ### Hexadecimal color Change the text color of an element using the hexadecimal color code. ```html

Aa

``` ### Variable alias --- ## Units ### Unit conversion ### Unit sensing ### Multiplier units --- ## Functions ### rgb(), hsl(), oklch(), ... Change the text color of an element using color functions like `rgb()`, `hsl()`, `oklch()`, and others. ```html

Aa

``` --- ## Combine with states and queries After the declaration itself is clear, you can attach selectors and conditions without changing the declaration syntax. ```html ``` This means: - `bg:blue-60` applies by default. - `bg:blue-70:hover@md` applies only when the button is hovered and the viewport matches `@md`. - `transition:background-color|.2s` adds a `background-color` transition. The rest of the syntax tutorial builds on this model: declarations first, then selectors, then queries. --- # Theme Tokens Source: https://rc.css.master.co/en/guide/theme Summary: Define shared design tokens with @theme for colors, spacing, typography, radius, breakpoints, containers, shadows, and motion. ## Overview Theme tokens are the shared design values a Master CSS project reaches for every day: colors, spacing, typography, radius, shadows, motion, breakpoints, and container sizes. Define tokens in the project CSS entry with `@theme`, then use short contextual classes in markup. Keep the page focused on values. Use [Global Styles](/guide/global-styles) for reusable components and utilities, [Conditional Queries](/guide/conditional-queries) for variants, and [Variables and Modes](/guide/variables-and-modes) for the underlying resolution model. ```css name=index.css @import '@master/css'; @theme { --color-brand: #4f46e5; --color-text-action: var(--color-brand); --spacing-lg: 1.5rem; --radius-lg: 1rem; --breakpoint-md: 48rem; --container-md: 28rem; } @theme light { --color-surface-card: #ffffff; } @theme dark { --color-surface-card: #111827; } ``` ```html
Settings
``` Master CSS resolves theme tokens before generating class rules. The generated CSS still uses normal CSS custom properties unless you intentionally define inline tokens. --- ## Project CSS entry A project needs a CSS entry that marks the Master CSS graph. Put shared tokens in the stylesheet that imports `@master/css`, or in CSS already imported by that entry. ```css name=index.css @import '@master/css'; @theme { --color-brand: #4f46e5; } ``` The important part is the graph, not a special file name. Theme tokens can live wherever the project CSS entry already reaches them. --- ## Define tokens Theme tokens are CSS custom property declarations inside `@theme` blocks. Write the full token name with the leading `--`. The prefix places the value in a namespace that Master CSS utilities already understand. ```css name=index.css @theme { --content-hash: " #"; --color-brand: #4f46e5; --color-text-action: var(--color-brand); --spacing-lg: 1.5rem; --font-family-sans: Geist, ui-sans-serif, system-ui, sans-serif; --radius-lg: 1rem; --breakpoint-md: 48rem; --container-md: 28rem; } @theme light { --color-surface-card: #ffffff; --shadow-card: 0 0 0 1px rgb(15 23 42 / .06), 0 16px 40px rgb(15 23 42 / .12); } @theme dark { --color-surface-card: #111827; --shadow-card: 0 0 0 1px rgb(255 255 255 / .06), 0 16px 40px rgb(0 0 0 / .36); } ``` Use token names that describe the shared decision, not the first component that needed the value. A `brand` color, `lg` spacing step, or `card` shadow can be reused. A token named after one button or one modal usually belongs closer to that component. --- ## Use tokens Utilities resolve token values from the namespace they use. The same short key can mean spacing in `p:lg`, radius in `r:lg`, a container width in `max-w:md`, or a breakpoint in `@md`. ```html ``` For a deeper explanation of namespace resolution and contextual lookup, see [Variables and Modes](/guide/variables-and-modes#namespace-resolution). --- ## Alias and override tokens Use native CSS `var()` when a token should reference another token. This keeps semantic roles tied to a smaller set of foundation values. ```css name=index.css @theme { --color-brand: #4f46e5; --color-text-action: var(--color-brand); } ``` Define the same token key as a preset token when you want to override it. Later definitions in the project CSS graph win. ```css name=index.css @theme { --color-blue: #4589ff; --spacing-lg: 1.625rem; } ``` Use overrides intentionally. If the whole product should use a different `blue` or `lg`, override the preset token. If only one product role changes, create a semantic token such as `color-text-action` or `shadow-card`. --- ## Add mode-aware values Use mode-specific `@theme` blocks when the same token should resolve differently in light, dark, or custom modes. ```css name=index.css @theme light { --color-surface-card: #ffffff; --color-text-card: #111827; --shadow-card: 0 0 0 1px rgb(15 23 42 / .06), 0 16px 40px rgb(15 23 42 / .12); } @theme dark { --color-surface-card: #111827; --color-text-card: #f9fafb; --shadow-card: 0 0 0 1px rgb(255 255 255 / .06), 0 16px 40px rgb(0 0 0 / .36); } ``` ```html
...
``` Keep the token name mode-neutral. Markup should say `surface-card` or `text-card`, not `dark-card`. For `mode-trigger`, `default-mode`, manual switches, and local mode islands, see [Variables and Modes](/guide/variables-and-modes#mode-triggers). --- ## Use inline and static tokens Use `@theme inline` when a token is only a utility shorthand and should not emit a CSS custom property. Master CSS still matches the token, but generated utilities write the resolved value directly. ```css name=index.css @theme inline { --color-brand: #4f46e5; --spacing-feature: 1.5rem; } ``` ```html
...
``` ```css .bg\:brand { background-color: #4f46e5; } .p\:feature { padding: 1.5rem; } ``` Inline tokens can reference other inline tokens. If an inline token references a regular theme token, Master CSS keeps the regular `var(--*)` reference and emits that regular token when needed. Inline tokens cannot be mode-specific; use normal `@theme light` and `@theme dark` blocks when a value must change by mode. Use `@theme static` when a token or managed keyframes definition should be emitted as an initial CSS resource instead of waiting for a matching class. ```css name=index.css @theme static { --color-brand: #4f46e5; } ``` --- ## Define responsive tokens Responsive thresholds are theme tokens too. Define `breakpoint` variables for viewport condition suffixes, and define `container` variables for container query thresholds and width caps. ```css name=index.css @theme { --breakpoint-sm: 40rem; --breakpoint-md: 48rem; --breakpoint-lg: 64rem; --container-sm: 24rem; --container-md: 28rem; --container-lg: 32rem; } ``` ```html
...
``` Keep breakpoint tokens broad and product-wide. Use container tokens when a reusable component should respond to the space it receives. See [Breakpoints](/guide/breakpoints) and [Containers](/guide/containers) for the responsive scales. --- ## Define motion tokens Motion values can be tokens too. Put reusable animation recipes, durations, easing curves, and managed keyframes in `@theme`. ```css name=index.css @theme { --duration-enter: 180ms; --easing-standard: cubic-bezier(.4, 0, .2, 1); --animate-dialog-in: dialog-in var(--duration-enter) var(--easing-standard) both; @keyframes dialog-in { from { translate: 0 0.5rem; opacity: 0; } to { translate: 0; opacity: 1; } } } ``` ```html ``` Keyframes are emitted outside cascade layers, while animation utilities still generate in the utilities layer. For motion naming and usage, see [Motion](/guide/motion) and [Animation](/reference/animation). --- ## Continue with foundation guides Use this page when you need to define or override project tokens. Continue into the design foundation guides for token-scale strategy: * [Colors](/guide/colors) * [Spacing](/guide/spacing) * [Typography](/guide/typography) * [Corner Radius](/guide/corner-radius) * [Elevation](/guide/elevation) * [Motion](/guide/motion) * [Breakpoints](/guide/breakpoints) * [Containers](/guide/containers) --- # Typography Source: https://rc.css.master.co/en/guide/typography Summary: Use text scale tokens, font utilities, line height, letter spacing, families, and weights. ## Overview Typography tokens define readable type scale, line height, letter spacing, font families, and font weights. Use `text:` when you want a complete type treatment, and use lower-level typography utilities when you need to tune one property. ```html

Readable product copy

``` --- ## Namespaces for typography Typography is built from [theme tokens](/guide/theme) organized into focused namespaces. Utilities search the relevant namespace, so `font:lg`, `leading:md`, and `tracking:tight` can use short token names without the full custom property prefix. --- ## All-in-one text scale At its core, the system is powered by a semantic type scale from `text:3xs` to `text:10xl`. These values are calibrated as complete text treatments, not just mathematically scaled font sizes. Use `text:` to apply the tuned font size, line height, and letter spacing with one class. * `text:3xs ~ text:xs` — For fine print, annotations, captions, or table labels * `text:sm ~ text:lg` — Standard text sizes for body copy, paragraphs, and buttons * `text:xl ~ text:3xl` — Ideal for subheadings, lead paragraphs, or callouts * `text:4xl ~ text:10xl` — Reserved for large headings, page titles, and hero sections Use `font:` when you only want the font-size token. Use `leading:*` and `tracking:*` when the design intentionally adjusts line height or letter spacing separately. ### Body text ### Headings ### Page titles ### Without vs with `text:` Manually configuring typography often requires juggling `font-size`, `line-height`, and `letter-spacing`. This becomes inconsistent when the same heading or paragraph style appears across components. font:5xl Designing for consistency across every platform. text:5xl Designing for consistency across every platform. (x) The type treatment is assembled manually. ```html

...

``` (o) The type treatment uses the shared text scale. ```html

...

``` The `text:3xl` token applies a finely tuned combination: Prefer `text:` for repeated body, heading, and display styles. Reach for lower-level typography utilities only when the design intentionally departs from the text scale. --- ## Type scale The font scale ranges from `font:3xs` to `font:10xl`, with each size intentionally designed to deliver visual harmony and clear hierarchy across a variety of use cases. --- ## Font families See the [font family](/reference/font-family) reference for more details on how to add custom fonts. --- ## Font weights Our typography system defines a semantic range of font weight tokens, from `font:thin` to `font:heavy`, providing clear naming for visual emphasis and typographic hierarchy. * `font:thin` extra-light strokes for subtle or elegant UI elements * `font:line` light weight, ideal for large headings or minimalist design * `font:regular` default weight for body text and general readability * `font:medium` slightly bolder for subheadings or emphasis * `font:bold` strong emphasis, often used in call-to-action or UI labels * `font:heavy` maximum weight for impact, branding, or visual anchors --- ## Line height --- ## Letter spacing --- # Variables and Modes Source: https://rc.css.master.co/en/guide/variables-and-modes Summary: Understand how Master CSS resolves theme variables, emits CSS custom properties, and applies light, dark, and custom modes. ## Overview Variables are the bridge between project vocabulary and generated CSS. Master CSS reads `@theme` blocks as manifest input, resolves token names into namespaces, and emits CSS custom properties only when a generated rule needs them. Modes are named buckets for alternate variable values. They let the same class string adapt to light, dark, high-contrast, or product-specific themes without duplicating markup. ```css name=index.css @import '@master/css'; @theme { --color-brand: #4f46e5; --spacing-card: 1.5rem; } @theme light { --color-surface-card: #ffffff; } @theme dark { --color-surface-card: #111827; } ``` ```html
``` --- ## Variable lifecycle `@theme`, `@settings`, and `@custom-variant` directives are manifest inputs. Master CSS reads them before class generation, then emits only the variables, keyframes, and generated rules that the application uses. ```css name=index.css @theme { --color-brand: #4f46e5; } ``` ```html ``` When `bg:brand` is generated, Master CSS resolves `brand` through the background color namespace and emits a declaration that references `--color-brand`. The variable itself is emitted in the `theme` layer. Regular CSS custom property behavior still applies. Values inherit through the DOM, cascade by selector, and compute where the browser sees the declaration. --- ## Namespace resolution A theme variable name has the shape `-`. Master CSS resolves the namespace by longest prefix, so `color-line-divider` belongs to `color-line`, not `color`. ```css name=index.css @theme { --color-brand: #4f46e5; --color-text-action: var(--color-brand); --color-line-divider: rgb(0 0 0 / 12%); --spacing-card: 1.5rem; --radius-card: 0.75rem; } ``` The utility decides which namespace it reads. The same key can mean different values in different contexts: ```html ``` Full property names do not become token namespaces automatically. A namespace is available only when the preset registers it and a utility or native value namespace references it. ### Default namespace sources The default theme vocabulary is registry-backed. This table lists the built-in condition namespace and the namespaces currently referenced by default utilities or native value namespaces. --- ## Contextual token lookup Contextual utilities keep class strings short by searching the namespace they already understand. | Class | Namespace searched | | --- | --- | | `p:md` | `spacing-md` | | `r:md` | `radius-md` | | `max-w:md` | `container-md` | | `@md` | `breakpoint-md` | | `text:body` | `color-text-body` | This is why token keys should be named for their namespace. `md` can work across spacing, radius, container, and breakpoint scales because the utility supplies the missing context. Use native CSS `var()` when a token should reference another theme token: ```css name=index.css @theme { --color-brand: #4f46e5; --color-text-action: var(--color-brand); } ``` --- ## Inline and static variables Regular theme variables emit CSS custom properties when generated rules need them. Inline variables behave like utility shorthands: Master CSS resolves the value and writes it directly into generated declarations. ```css name=index.css @theme inline { --color-brand: #4f46e5; --spacing-feature: 1.5rem; } ``` ```html
...
``` ```css .bg\:brand { background-color: #4f46e5; } .p\:feature { padding: 1.5rem; } ``` Inline variables can reference other inline variables. If an inline variable references a regular theme variable, Master CSS keeps the regular `var(--*)` reference and emits that dependency when needed. Inline variables cannot be mode-specific. Use `@theme static` when a variable or managed keyframes definition should be emitted as an initial CSS resource instead of waiting for a matching class. ```css name=index.css @theme static { --color-brand: #4f46e5; @keyframes fade-in { to { opacity: 1; } } } ``` `inline` and `static` cannot be combined. --- ## Mode buckets `light` and `dark` are always available. Defining another mode adds it to the theme automatically. ```css name=index.css @theme light { --color-surface-card: #ffffff; --color-text-card: #111827; } @theme dark { --color-surface-card: #111827; --color-text-card: #f9fafb; } @theme contrast { --color-surface-card: #000000; --color-text-card: #ffffff; } ``` ```html
...
``` When a token has mode-specific values, generated utilities reference the same CSS custom property. The active mode changes the variable value, not the class name. ### Derived mode-aware values Default theme variables are emitted on `:root`. If a default variable references a mode-specific variable, the browser computes the derived custom property where it is declared. A local `.dark` or `:host(.dark)` island can override the referenced token, but it does not recompute an inherited derived token. ```css name=index.css @theme { --stripe: linear-gradient(135deg, var(--color-line-muted) 4.5%, var(--color-surface-raised) 0); } ``` Define derived tokens inside each mode bucket when they must follow local mode islands: ```css name=index.css @theme light { --stripe: linear-gradient(135deg, var(--color-line-muted) 4.5%, var(--color-surface-raised) 0); } @theme dark { --stripe: linear-gradient(135deg, var(--color-line-muted) 4.5%, var(--color-surface-raised) 0); } ``` This is CSS custom property computed-value behavior, not a Master CSS selector issue. --- ## Mode triggers `mode-trigger` controls how mode buckets are emitted. ```css name=index.css @settings { default-mode: light; mode-trigger: media; } ``` | Trigger | Output behavior | | --- | --- | | `media` | Uses `@media (prefers-color-scheme: )` for light and dark modes. | | `class` | Uses class wrappers such as `.dark &`. Built-in `light` and `dark` mode buckets also emit native `color-scheme`. | | `host` | Uses shadow host wrappers such as `:host(.dark) &`. Built-in `light` and `dark` host buckets also emit native `color-scheme`. | `default-mode` controls which class-triggered or host-triggered mode also attaches to `:root` or `:host`. Set `default-mode: none;` when no mode should be applied by default. It has no effect with `mode-trigger: media`, because the browser decides the active color scheme from user or system preferences. For manual theme switches, set `mode-trigger` to `class`: ```css name=index.css @settings { mode-trigger: class; default-mode: light; } ``` ```html
...
``` Custom modes work best with `class` or `host`. Browsers only support `light` and `dark` values for `prefers-color-scheme`, so custom modes cannot work as native media-triggered color schemes. --- ## Project settings Settings are not design tokens, but a few of them shape variable and class output. ```css name=index.css @settings { root-size: 16; base-unit: 4; scope: #app; } ``` `root-size` controls numeric conversion to root-relative units such as `rem`. `base-unit` controls multiplier units such as `1x`, `2x`, and `4x`. `scope` prefixes generated selectors when Master CSS should only style a specific application root. For the complete directive syntax, see [Directives](/guide/directives). For authoring shared design vocabulary, see [Theme Tokens](/guide/theme). --- # View Transitions Source: https://rc.css.master.co/en/guide/view-transitions Summary: Create state and page transitions with the browser View Transition API and Master CSS syntax. ## Overview The [View Transition API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) creates animated transitions between two visual states. It can handle same-document updates in an SPA and same-origin navigation between documents in an MPA. In a same-document transition, call `document.startViewTransition()` and update the DOM inside its callback. The browser snapshots the old state, runs the update, snapshots the new state, then animates the old and new snapshots. Without custom CSS, the default transition is a smooth cross-fade. (click) Select a view to run a same-document transition. ```js name=transition.js const update = () => { document.querySelector('[data-current-view]').textContent = 'Product detail' } if (!document.startViewTransition) { update() } else { document.startViewTransition(update) } ``` The demo uses Master CSS classes to name the snapshots that should transition independently: ```html

Product detail

``` Master CSS keeps the CSS side concise by expressing `view-transition-name`, `view-transition-class`, and native view-transition pseudo-elements directly in class names: | Class syntax | Use | | --------------------- | ---------------------------------------------------------------- | | `view-transition-name` | Names an element snapshot so it can animate apart from the root. | | `view-transition-class` | Groups named snapshots for shared pseudo-element styling. | | `::view-transition` | Targets the root view-transition pseudo-element tree. | | `::view-transition-group()` | Styles the group box for a named snapshot. | | `::view-transition-image-pair()` | Styles the wrapper around the old and new snapshot images. | | `::view-transition-old()` | Styles the outgoing snapshot image. | | `::view-transition-new()` | Styles the incoming snapshot image. | --- ## Article list to detail A common use case is moving from an article feed to an article detail page. The selected article's image, title, and date can keep the same `view-transition-name` in both layouts, while the surrounding card grid and detail content change normally. This demo also uses `view-transition-class` so the transition timing applies only to article snapshots. (click) Click Read More, then return to the article list. In the list view, every article gets unique names for its shared elements: ```html
A mountain ridge under soft light

Designing transitions that preserve context

...

``` In the detail view, render the same image, date, and title with the same names: ```html
A mountain ridge under soft light

Designing transitions that preserve context

...

``` The state update can stay framework-free. Replace the list with the detail markup inside `startViewTransition()`: ```js const root = document.querySelector('[data-articles]') const detailTemplate = document.querySelector('#article-detail') document.querySelector('[data-read-more]').addEventListener('click', () => { const update = () => { root.replaceChildren(detailTemplate.content.cloneNode(true)) } if (!document.startViewTransition) { update() } else { document.startViewTransition(update) } }) ``` {[ 'view-transition-name:article-image', 'view-transition-name:article-date', 'view-transition-name:article-title', 'view-transition-class:article', 'animation-duration:.52s::view-transition-group(.article)' ]} (i) Only one rendered element can use the same `view-transition-name` at a time. The list uses article-specific names such as `article-aurora-image`, `article-studio-image`, and `article-coast-image` so the selected card can match the detail page without colliding with other cards. --- ## Naming snapshots By default, a view transition animates the `root` snapshot. Use `view-transition-name`, the [`view-transition-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/view-transition-name) property, when one element needs to move, resize, or fade separately from the rest of the page. ```html
...
``` The same `view-transition-name` must be unique in the rendered document. If two rendered elements have the same name at the same time, the transition is skipped. For lists that need automatic per-element names in same-document transitions, native CSS also provides `match-element`. ```html
  • ...
  • ``` Use `view-transition-name:none` to keep an element out of its own separate snapshot. ```html ``` --- ## Styling transition pseudo-elements The browser exposes transition snapshots through pseudo-elements such as `::view-transition-group()`, `::view-transition-old()`, and `::view-transition-new()`. MDN recommends styling the group when the same duration or timing should apply to both the old and new snapshots. In Master CSS, write the pseudo-element after the declaration: ```html ``` {[ 'animation-duration:slow::view-transition-group(hero)', 'animation:fade|fast|both|reverse::view-transition-old(hero)', 'animation:fade|fast|both::view-transition-new(hero)' ]} (i) Apply these classes to the `html` element when you style global view-transition pseudo-elements. The pseudo-element tree is generated from the document root, so a class on an ordinary descendant will generate CSS but will not match the root transition pseudo-elements. You can also group related named snapshots with `view-transition-class` and then target the class selector in the pseudo-element argument: ```html
    ...
    ``` --- ## Cross-document transitions For same-origin MPA navigation, opt in with native CSS in both the current and destination documents: ```css name=app.css @view-transition { navigation: auto; } ``` No JavaScript is required for the navigation itself. You can still use Master CSS on elements that should become named snapshots across pages: ```html
    ...
    ``` If both documents render one `product-hero` snapshot, the browser can animate that element between pages. If either page renders zero or more than one matching snapshot, the named transition will not run as intended. --- ## Fallbacks View transitions are progressive enhancement. Always keep the DOM update valid without animation: ```js const update = () => renderNextState() if (!document.startViewTransition) { update() } else { document.startViewTransition(update) } ``` --- ## Reduced motion After the core transition works, add a motion preference layer. You can scope animation classes with `@motion`, which maps to `@media (prefers-reduced-motion: no-preference)`. ```html ``` Or skip the transition in JavaScript for motion-sensitive users: ```js const shouldReduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches if (!document.startViewTransition || shouldReduceMotion) { update() } else { document.startViewTransition(update) } ``` See MDN's [Using the View Transition API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API/Using) and web.dev's [View transitions for single page applications](https://web.dev/learn/css/view-transitions-spas) for deeper API behavior and browser examples. --- # Console Messages Source: https://rc.css.master.co/en/messages Summary: Errors and warnings you may encounter when using Master CSS. ## Errors ## Warnings --- # Hydration Errors Source: https://rc.css.master.co/en/messages/hydration-errors Summary: There was a difference between the CSS rules that was pre-rendered from the server and the Master CSS rules that was rendered during the first render in the browser. ## Causes ### Why this error occurred 1. The server's compiled project manifest does not match the client's. 2. The server's version does not match the client's. --- ## Solutions ### Import the same manifest ```ts name=server.ts import manifest from 'virtual:master-css-manifest' ``` ```ts name=client.ts import manifest from 'virtual:master-css-manifest' ``` --- # Missing Master CSS entry Source: https://rc.css.master.co/en/messages/missing-master-css Summary: The integration could not find a project CSS entry for the shared MasterCSSManifest, editor tooling, and build integration behavior. ## Causes ### Why this warning occurred An integration started without finding a project CSS entry in the current project directory. ```txt [@master/css.vite] Master CSS entry was not found in /path/to/project. Create /path/to/project/index.css and mark it as the project entry, for example: @import "@master/css"; @import "./src/globals.css"; Master CSS uses this entry graph for integrations, language service, and VS Code. Imported CSS manifest directives participate in the graph. ``` Master CSS can still generate utility CSS without a project entry, but integrations and editor tooling use the project CSS entry to compile the shared MasterCSSManifest for tokens, component definitions, animations, and workspace behavior. `@theme`, `@settings`, `@custom-variant`, and managed definition directives do not have to be written directly in the entry file. They can live in ordinary CSS files such as `src/globals.css` or `app/globals.css`, as long as the entry imports those files with a relative CSS import. The normal app entry imports `@master/css`; the lightweight `@master entry;` marker is also recognized when a stylesheet intentionally should not load the package stylesheet graph. --- ## Solutions ### Create a workspace entry Create `index.css` at the project root and import your stylesheet entry. ```css name=index.css @import '@master/css'; @import './src/globals.css'; ``` Then keep tokens, component rules, animations, or other Master CSS manifest directives in that imported stylesheet or in files imported by it. ```css name=src/globals.css @theme { --color-primary: #4f46e5; } @components { btn { @compose inline-flex items-center h:40px px:md r:md bg:primary fg:white; } } ``` Ordinary CSS outside Master CSS directives stays native CSS and follows the integration's stylesheet behavior. ### Import an explicit manifest resource If runtime code should intentionally use one CSS resource instead of the discovered project-level entry, import that resource with `?master-css-manifest`. ```ts name=src/main.ts import CSSRuntime from '@master/css-runtime' import manifest from './theme.css?master-css-manifest' CSSRuntime.create({ manifest }).observe() ``` For lower-level APIs that accept a compiled manifest directly, pass a `MasterCSSManifest` through their `manifest` option. ### Ignore the warning You can ignore this warning when the current project intentionally has no project CSS entry and does not need shared tokens, component definitions, animations, language-service workspace detection, or editor integration behavior. --- # API Reference Source: https://rc.css.master.co/en/reference Summary: This section provides detailed reference documentation for working with Master CSS. {categories .filter(category => category.name !== 'Overview') .map(category => (

    {category.name}

    ))} --- # accent-color Source: https://rc.css.master.co/en/reference/accent-color Summary: Setting the accent color of user interface elements or controls. ## Overview ## Basic usage ### Set the accent color Use the `accent-color:color` to set a custom accent color of user interface elements or controls. ```html ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    …
    ``` --- # align-content Source: https://rc.css.master.co/en/reference/align-content Summary: Controlling how multiple rows or columns are aligned along its cross axis. ## Overview ## Examples ### Align multiple rows or tracks Use `content-*` utilities to distribute rows in a multi-line flex container or tracks in a grid container along the cross axis. ```html
    ...
    ``` ### Center wrapped lines Use `content-center` when the group of rows should sit in the middle of the container. ```html
    ...
    ``` `align-content` needs extra space in the cross axis. If there is only one line or no free space, it may not visibly change the layout. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use [align-items](/reference/align-items) for item alignment within each row. --- # align-items Source: https://rc.css.master.co/en/reference/align-items Summary: Controlling how items are aligned along its cross axis. ## Overview ## Examples ### Align items on the cross axis Use `items-*` utilities to align flex or grid items on the cross axis. In a default row flexbox, the cross axis is vertical. ```html
    Aron
    ``` ### Align to the start or end Use `items-start` or `items-end` when children should align to one edge of the cross axis. ```html

    Longer text can wrap without vertically centering against the media.

    ``` ### Stretch children Use `items-stretch` when children should fill the cross size of the container. The container needs a definite cross size for the stretch to be visible. ```html
    One
    Two
    ``` ### Align text baselines Use `items-baseline` when inline text in differently sized children should sit on the same baseline. ```html
    24 messages
    ``` For one item only, use [align-self](/reference/align-self). ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use [justify-content](/reference/justify-content) for the main axis. --- # align-self Source: https://rc.css.master.co/en/reference/align-self Summary: Controlling how an individual item is aligned along its cross axis. ## Overview ## Examples ### Override cross-axis alignment for one item Use `self-*` utilities when a single flex or grid item needs different cross-axis alignment than its siblings. ```html

    Text that controls the row height.

    ``` ### Stretch a single item Use `self-stretch` when one child should fill the cross size even if the group alignment is different. ```html ``` Use [align-items](/reference/align-items) when all items should share the same alignment. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` The effect depends on the parent layout mode and axis. --- # animation Source: https://rc.css.master.co/en/reference/animation Summary: Applying an animation between styles. ## Overview ## Basic usage Use `animate:*` to apply a named animation token from the `animate` namespace. Use the native `animation:*` shorthand when you want to write the keyframe name, duration, easing, fill mode, and other animation parts together. ### Ping indicator Use the `ping` animation to indicate that the shop is open. ```html ``` ### Rotate indicator Use the counterclockwise `rotate` animation to indicate that data is being restored. ```html ``` --- ## Advanced usage ### Loading spinner Use the `fade` animation on SVG paths with regular delays to create a loading spinner. ```html ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    …
    ``` --- ## Customization ### Add your animations Customize managed CSS animations with [`@theme` keyframes](/guide/motion#customize-motion-tokens). --- # animation-delay Source: https://rc.css.master.co/en/reference/animation-delay Summary: Setting a time to delay before beginning to perform the animation. ## Overview ## Examples ### Delay animation start Use `animation-delay:*` to wait before the first animation cycle begins. ```html
    Staggered item
    ``` ### Offset looping animations Negative delays start an animation partway through its cycle. This is useful for spinner segments that should not all begin at the same frame. ```html ... ``` ### Stagger a list Apply increasing delays to siblings when each item should enter after the previous one. ```html
  • One
  • Two
  • Three
  • ``` ### Use duration tokens Define `duration-*` tokens when the same delay appears across several animation patterns. This example assumes your project defines a `fade` keyframe. ```css name=index.css @theme { --duration-stagger: 120ms; } ``` ```html
  • ...
  • ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-direction Source: https://rc.css.master.co/en/reference/animation-direction Summary: Setting the direction of the animation. ## Overview Use the native animation direction property directly. ```html
    ``` --- ## Basic usage ### Play forward The animation plays forward in each cycle. ### Play backward The animation plays backward in each cycle. For example, rotate counterclockwise. ### Play alternately The animation **reverses direction each cycle** and **the first iteration plays forward**. ### Play alternately and reverse first The animation **reverses direction each cycle** and **the first iteration plays backward**. ### Fade out Reverse a project-defined `fade` keyframe so that you don't need to define a new keyframe for `fade-out`. ```html … ``` For one-shot animations, remove `infinite`. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    …
    …
    …
    …
    ``` --- # animation-duration Source: https://rc.css.master.co/en/reference/animation-duration Summary: Setting the length of time that an animation takes to complete one cycle. ## Overview ## Examples ### Set animation speed Use `animation-duration:*` to define how long one cycle of the keyframes takes. ```html
    Fades in
    ``` ### Slow down looping motion Looping indicators should often use a steady, readable duration so they do not distract from nearby content. ```html ... ``` ### Remove animation in static output Use `animation-duration:0ms` when an animation should resolve immediately in print or other static contexts. ```html
    Static print state
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-fill-mode Source: https://rc.css.master.co/en/reference/animation-fill-mode Summary: Setting how a CSS animation applies styles to its target before and after its execution. ## Overview ## Examples ### Keep the final keyframe Use `animation-fill-mode:forwards` when the element should keep the values from the final keyframe after the animation completes. ```html
    Remains visible
    ``` ### Apply both before and after states Use `animation-fill-mode:both` when the element should use the first keyframe during a positive delay and keep the final keyframe after completion. ```html
    Delayed entrance
    ``` ### Reset fill behavior Use `animation-fill-mode:none` when the element should return to its ordinary styles before and after animation. ```html
    Uses base styles outside the animation
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-iteration-count Source: https://rc.css.master.co/en/reference/animation-iteration-count Summary: Setting the number of times an animation should be played. ## Overview ## Examples ### Loop animation Use `animation-iteration-count:infinite` when an animation should repeat until the state changes. ```html
    Loading
    ``` ### Specify N iterations Use a number for one-shot or limited loops. Decimal values are valid when you need an animation to stop partway through a cycle. ```html
    Repeats three times
    ``` ### Pair with fill mode When the last iteration should leave the element in its final state, combine the count with `animation-fill-mode:forwards` or `animation-fill-mode:both`. ```html
    Ends at the final keyframe
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-name Source: https://rc.css.master.co/en/reference/animation-name Summary: Setting the names of the animation. ## Overview ## Examples ### Choose the keyframes to run Use `animation-name:*` to select a named keyframes rule while controlling the other animation parts separately. ```html
    Saved
    ``` ### Disable an animation Use `animation-name:none` when the element should keep the rest of its animation settings but stop running keyframes in a specific condition. ```html
    No animation in print
    ``` ### Combine with timing longhands The name alone does not define how long the animation runs. Pair it with duration, timing, delay, iteration count, and fill mode as needed. ```html Appears once ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-play-state Source: https://rc.css.master.co/en/reference/animation-play-state Summary: Setting whether an animation is running or paused. ## Overview ## Examples ### Run an animation Use `animation-play-state:running` to ensure an animation is active when another state may pause it. ```html
    Running
    ``` ### Pause animation Use `animation-play-state:paused` when an animation should stop without resetting its current frame. ```html ``` ### Pause nonessential motion Pause decoration when the user is interacting with the control or when the motion would compete with a more important state. ```html
    Interactive panel
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # animation-timing-function Source: https://rc.css.master.co/en/reference/animation-timing-function Summary: Setting speed curve of the animation. ## Overview ## Examples ### Set keyframe easing Use `animation-timing-function:*` to control how keyframes progress between each keyframe stop. ```html
    Enters
    ``` ### Use linear timing for rotation Continuous indicators usually need `linear` so the motion does not speed up and slow down every cycle. ```html ... ``` ### Match easing to intent Use `ease-out` for entrance motion and `ease-in` for exit motion. Prefer `linear` for clocks, progress, and loading rotation. ```html
    Dismiss
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # appearance Source: https://rc.css.master.co/en/reference/appearance Summary: Controlling the native appearance of UI controls. ## Overview ## Examples ### Remove default styling Use `appearance:none` to remove the browser's native control styling before applying your own visual treatment. ```html ``` ### Restore native appearance Use `appearance:auto` when a variant should return to the platform control instead of the custom one. ```html ``` ### Keep semantics intact `appearance:none` only changes rendering. Keep using the correct form element and accessible label. ```html ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html ``` --- # aspect-ratio Source: https://rc.css.master.co/en/reference/aspect-ratio Summary: Setting the ratio for the box. ## Overview ## Examples ### Set a custom ratio Use `aspect-ratio:` to reserve a proportional box before media or content finishes loading. ```html ``` ### Use square and video shortcuts Use `square` for `1 / 1` and `video` for a common widescreen media frame. ```html
    ``` ### Pair with one explicit axis Aspect ratio needs at least one axis to be resolved by width, height, or content. The common pattern is a fluid width with an aspect ratio. ```html
    ...
    ``` If both width and height are fixed, the browser follows those dimensions and the ratio is only a preferred constraint. ### Use the video shortcut Use `video` when you need the common `16 / 9` media frame. ```html
    ...
    ``` ### Choose size for fixed squares Use [size](/reference/size) for fixed square UI elements. Use `aspect-ratio:*` when at least one axis should remain fluid. ```html ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use `object-cover` or `object-contain` on replaced media when the content should adapt inside the reserved ratio. --- # backdrop-filter Source: https://rc.css.master.co/en/reference/backdrop-filter Summary: Style syntax for applying filter effects to the area behind an target element. ## Overview ## Examples ### Blur content behind an element Use `backdrop-filter:blur(...)` to apply a backdrop filter to pixels behind the element. ```html
    ...
    ``` ### Combine with translucent backgrounds Backdrop filters are only visible when the element lets the backdrop show through, usually with an alpha background. ```html
    ...
    ``` ### Reset backdrop filters Use `backdrop-filter:none` to disable a backdrop filter. ```html
    ...
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Backdrop filters can be costly and browser-dependent; verify important surfaces in target browsers. --- # background Source: https://rc.css.master.co/en/reference/background Summary: Setting all background style properties at once. ## Overview ## Examples ### Use the background shorthand Use `bg:*` with pipe separators when several background longhands should be set together. ```html
    ...
    ``` ### Prefer focused utilities for simple changes Use [background-color](/reference/background-color), [background-image](/reference/background-image), [background-position](/reference/background-position), [background-size](/reference/background-size), and [background-repeat](/reference/background-repeat) when only one background part should change. ```html
    ...
    ``` The native `background` shorthand resets several background longhands. Use it intentionally when that reset is part of the design. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use layered backgrounds with comma-separated values only when the visual needs multiple images or gradients. --- # background-attachment Source: https://rc.css.master.co/en/reference/background-attachment Summary: Setting whether position of background image is fixed when scrolling. ## Overview ## Examples ### Scroll with the element Use `bg-scroll` for the normal background attachment behavior. ```html
    ...
    ``` ### Fix a background to the viewport Use `bg-fixed` when the background should stay fixed relative to the viewport. ```html
    ...
    ``` Fixed backgrounds can behave differently on mobile browsers. Keep the effect decorative and verify it on target devices. ### Attach to scrollable content Use `bg-local` when the background should scroll with the element's contents. ```html
    ...
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use motion and contrast carefully when fixed backgrounds sit behind text. --- # background-blend-mode Source: https://rc.css.master.co/en/reference/background-blend-mode Summary: Setting how an element's background images should blend with the background color. ## Overview ## Examples ### Blend background layers Use `background-blend-mode:*` when multiple background layers or a background image and color should blend together. ```html
    ...
    ``` ### Restore normal blending Use `background-blend-mode:normal` to remove a blend mode at a breakpoint or state. ```html
    ...
    ``` For blending the whole element with content behind it, use [mix-blend-mode](/reference/mix-blend-mode). ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Check contrast after blending, especially when text sits on top of the background. --- # background-clip Source: https://rc.css.master.co/en/reference/background-clip Summary: Controlling how clip the background. ## Overview ## Examples ### Clip a background to a box Use `bg-clip-border`, `bg-clip-padding`, or `bg-clip-content` to control where the background is painted. ```html
    ...
    ``` ### Clip a background to text Use `bg-clip-text` with a transparent text fill when a gradient or image should show through the glyphs. ```html

    Gradient text

    ``` Use this for display text, not body copy, because it can reduce contrast and selection readability. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use [background-origin](/reference/background-origin) when the issue is positioning rather than painting. --- # background-color Source: https://rc.css.master.co/en/reference/background-color Summary: Setting the background color of an element. ## Overview --- ## Basic usage ### With opacity Add the suffix `/alpha` to change the opacity of any color. Use `bg:*` for preset palette colors, project theme colors, and one-off colors. ```html
    ...
    Badge ``` Use alpha suffixes for local overlays, badges, and hover states. Add project theme colors only when a repeated color decision needs a shared name. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # background-image Source: https://rc.css.master.co/en/reference/background-image Summary: Setting background images on an element. ## Overview ## Examples ### Add a background image Use `bg:url(...)` to set `background-image`. ```html
    ...
    ``` ### Use gradients Use native CSS gradient functions directly in the class. ```html
    ...
    ``` Pair image utilities with [background-position](/reference/background-position), [background-size](/reference/background-size), and [background-repeat](/reference/background-repeat) unless you intentionally want the full [background](/reference/background) shorthand. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Use local or bundled assets according to the framework integration you are using. --- # background-origin Source: https://rc.css.master.co/en/reference/background-origin Summary: Setting the background's origin. ## Overview ## Examples ### Choose the background positioning area Use `bg-origin-padding`, `bg-origin-border`, or `bg-origin-content` to decide which box positions the background image. ```html
    ...
    ``` ### Align art with borders or content Use `bg-origin-border` when the background should start from the border box, and `bg-origin-content` when it should align with the content box. ```html
    ...
    ...
    ``` This affects positioning and sizing, not clipping. Use [background-clip](/reference/background-clip) to control where the background is painted. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` --- # background-position Source: https://rc.css.master.co/en/reference/background-position Summary: Setting the initial position for background image. ## Overview ## Examples ### Position a background image Use `bg-center`, `bg-top`, `bg-right`, `bg-bottom`, or `bg-left` to set `background-position`. ```html
    ...
    ``` ### Use explicit positions Use `background-position:*` when you need two-value or measured positions. ```html
    ...
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Position changes are most visible when the image is larger than the background area or when `bg-cover` crops the image. --- # background-repeat Source: https://rc.css.master.co/en/reference/background-repeat Summary: Setting how background images are repeated. ## Overview ## Examples ### Disable tiling Use `bg-no-repeat` when a background image should render once. ```html
    ...
    ``` ### Repeat on one axis Use `bg-repeat-x` or `bg-repeat-y` for stripes, dividers, and patterned backgrounds. ```html
    ...
    ``` Use `background-repeat:*` for values that do not have a shortcut. ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Most photographic backgrounds should use `bg-no-repeat`; repeating is mainly for patterns. --- # background-size Source: https://rc.css.master.co/en/reference/background-size Summary: Setting the size of the background image. ## Overview ## Examples ### Cover a frame Use `bg-cover` when the background image should fill the element and may be cropped. ```html
    ...
    ``` ### Contain an image Use `bg-contain` when the entire background image should remain visible. ```html
    ...
    ``` ### Use measured sizes Use `background-size:*` for measured or multi-layer sizes. ```html
    ...
    ``` ### Apply conditionally Apply styles based on different states using [selectors](/guide/state-selectors) and [conditional queries](/guide/conditional-queries). ```html
    ...
    ``` Pair size with [background-position](/reference/background-position) to control the crop. --- # border Source: https://rc.css.master.co/en/reference/border Summary: Setting an element’s border. ## Overview ## Examples ### Set width, style, and color together Use `b:|