Theming
Define design tokens as CSS custom properties, add a dark palette, switch themes at run time, and build components that follow the theme.
A theme keeps your interface's colours, spacing, radii and type in one place, so you can change them without touching any component's styles. In zgui a theme is a set of CSS custom properties. This page covers the framework mechanics; for the tokens the component library ships, see Tokens and theming.
Read Styling first.
Define tokens
A design token is a CSS custom property: a name starting with -- that inherits and is read with
var(). There is no token type, registry or build step.
Declare your tokens on :root, so every element inherits them:
use zgui::prelude::*;
const TOKENS: &str = css!(
":root {
--surface: #ffffff;
--surface-raised: #f7f8fa;
--ink: #1c2024;
--ink-muted: #60646c;
--accent: #0090ff;
--accent-ink: #ffffff;
--danger: #e5484d;
--border: #d9d9e0;
--radius: 8px;
--space: 12px;
}"
);Then read them in your rules:
.card {
background-color: var(--surface-raised);
color: var(--ink);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: var(--space);
}
/* A fallback for when the token is not declared. */
.progress__fill { width: var(--progress-fraction, 0%) }A token can hold any CSS value: a colour (hsl(210 100% 50%)), a length (12px), a shorthand
(0 1px 2px rgba(0, 0, 0, 0.3)), a timing function (cubic-bezier(0, 0, 0.2, 1)), or another token
(var(--surface)).
A misspelt token name produces no error or log. The declaration becomes invalid at computed-value time and the property falls back to its inherited or initial value. Check the spelling on both sides.
Why tokens go on :root
:root matches the element the runtime creates for each window. Both your view and the overlay
layers sit under it:
- root
:root matches this runtime-created element.
- overlay_root
- Content band
data-layer=content - Popover band
data-layer=popover - Modal band
data-layer=modal - Toast band
data-layer=toast
- Your application view
Everything the view builds.
Do not declare tokens on your outermost element. Menus, dialogs and toasts rendered through Portal
are children of the root, not of your view, so they would not inherit them. See
Overlays and portals.
A view cannot set attributes on the root element, so root tokens always come from a style sheet.
Set the framework's --zgui-* properties
The framework's own style sheet reads two custom properties that your theme should set:
:root {
--zgui-foreground: var(--ink); /* the root element's `color` */
--zgui-ring: var(--accent); /* the `:focus-visible` outline colour */
}The other --zgui-* properties are listed in the reference at the
end of this page.
Add a dark theme
Keep one set of token names and give them two palettes. Rules read only the names, so switching palettes changes no rule. You can switch on the desktop's setting or on your own class.
Follow the desktop setting
prefers-color-scheme follows the desktop's light or dark setting. No Rust code is needed:
:root {
--surface: #ffffff;
--ink: #1c2024;
--border: #d9d9e0;
}
@media (prefers-color-scheme: dark) {
:root {
--surface: #111113;
--ink: #edeef0;
--border: #363a3f;
}
}The window reads the setting before the first frame and tracks changes, so an application started on a dark desktop is dark from its first frame.
Let the user choose
Put the dark palette behind a class your program toggles:
.dark { --surface: #111113; --ink: #edeef0; --border: #363a3f; }column(class = "page", class:dark = move || dark.get()) {
box(class = "card") {
label {"Storage"}
}
}The tokens now inherit from that element down. Portalled content is not below it, so to reach
overlays either add the class to the portalled subtree too, or replace a :root sheet instead (see
Switch themes at run time).
The two approaches combine: keep the media query as the default and add .light and .dark
classes after it. A class rule has the same specificity as the :root rule and comes later, so it
wins where it is applied.
Which to use
| Media query | Class or sheet | |
|---|---|---|
| Decided by | the desktop | your program |
| User can pick a theme in your app | no | yes |
| Can be persisted | no | yes |
| Reaches portalled content | yes, when on :root | a :root sheet does; a class only where it is applied |
| Built-in scrollbars follow it | yes | when the rule sets color-scheme |
The framework's built-in scrollbars follow the scroll container's color-scheme. A theme rule
that sets color-scheme: dark gets the dark scrollbar paint on a light desktop. Without it, the
scrollbars follow the window's light or dark scheme. --zgui-scrollbar-thumb and
--zgui-scrollbar-track set their colours. See Scrolling.
Set the window's colour scheme
app().with_theme(scheme), WindowOptions::with_theme(scheme) and
WindowHandle::set_theme(Option<scheme>) take a zgui::platform::ColorScheme. They ask the
platform to present a window as light or dark (its title bar and decorations); set_theme(None)
returns the window to the desktop's setting.
This is a request. Some backends, such as the native Wayland backend, ignore it. Do not rely on it
to drive prefers-color-scheme; use a class or a sheet for an in-app theme choice.
Switch themes at run time
To switch the whole application, including overlays, replace a :root sheet. These prelude
functions manage sheets at run time (Styling has the details):
Prop
Type
Use the Stylesheet guard for a theme, so the sheet goes away with the view that chose it. The
Theme component in the complete example does this. Use install_stylesheet
for a component's own fixed rules.
A sheet installed while a view is being built applies in the same frame, so a component is styled by its own sheet in the frame it first appears.
Add an optional override
For an override that is only sometimes active, such as high contrast, install and remove it by name:
let overriding = RenderEffect::new(move |_| {
if contrast.get() {
install_stylesheet("contrast", ":root { --border: #000000; --ink: #000000 }");
} else {
remove_stylesheet("contrast");
}
});
on_cleanup_local(move || drop(overriding));Sheets cascade in installation order, so install an override after the theme sheet. Removing it restores the theme's values. To change a sheet later, replace it under the same name: removing and re-adding it moves it to the end of the cascade.
Override a token for one subtree
var:--name sets a custom property on one element from a view. Because it inherits, an override on
a container restyles its whole subtree:
column(class = "panel", var:--accent = "#8e4ec6") {
label(class = "panel__title") {"Danger zone"}
control(class = "btn", attr:data-tone = "accent") {"Delete"}
}The name must start with -- (var:accent is a compile error). The value is reactive and takes
Option<String>; None removes the property:
box(var:--space = move || Some(format!("{}px", spacing.get())))Keep var: overrides on containers rather than on every row of a long list. An element that
declares its own custom property is restyled whenever a custom property above it changes.
Build components that follow the theme
A themed component holds no colours. Its scoped sheet chooses which token each part uses; the theme
decides each token's value. Styling covers style! and variants! in full.
style! { pub CardStyle =>
":scope {
display: flex;
flex-direction: column;
gap: var(--space);
padding: var(--space);
border: 1px solid var(--border);
border-radius: var(--radius);
background-color: var(--surface-raised);
color: var(--ink);
}"
":scope > .title { font-weight: 600 }"
":scope > .note { color: var(--ink-muted) }"
}
#[component]
fn Card(#[prop(into)] title: String, children: Children) -> impl IntoView {
// Installing the same name and text again does nothing, so every card can call this.
install_stylesheet("card", CardStyle::CSS);
view! {
column(class = CardStyle::CLASS) {
label(class = "title") {{title}}
{children.into_view_once()}
}
}
}style! installs nothing by itself. Call install_stylesheet(name, CardStyle::CSS) and put
CardStyle::CLASS on the component's outermost element, or it renders unstyled without an error.
For visual options such as tone or size, variants! writes one data- attribute per option, and
the sheet maps each value to tokens:
variants! {
pub ButtonVariants {
base: "btn",
tone: { Neutral => "", Accent => "", Danger => "" } = Neutral,
}
}.btn {
border-radius: var(--radius);
border: 1px solid var(--border);
background-color: var(--surface-raised);
color: var(--ink);
}
.btn[data-tone="accent"] { background-color: var(--accent); color: var(--accent-ink) }
.btn[data-tone="danger"] { background-color: var(--danger); color: var(--accent-ink) }The component writes class = variants.classes() and the data-tone attribute from
variants.data_attributes() (Define variants).
Complete example
Two palettes as :root sheets, a Theme component that installs one and follows a signal, and a
page using the Card from above.
use zgui::prelude::*;
use zgui::reactive::RenderEffect;
const LIGHT: &str = ":root {
--surface: #ffffff; --surface-raised: #f7f8fa; --ink: #1c2024; --ink-muted: #60646c;
--accent: #0090ff; --accent-ink: #ffffff; --border: #d9d9e0;
--radius: 8px; --space: 12px;
--zgui-foreground: var(--ink); --zgui-ring: var(--accent);
}";
const DARK: &str = ":root {
--surface: #111113; --surface-raised: #18191b; --ink: #edeef0; --ink-muted: #b0b4ba;
--accent: #3b9eff; --accent-ink: #ffffff; --border: #363a3f;
--radius: 8px; --space: 12px;
--zgui-foreground: var(--ink); --zgui-ring: var(--accent);
}";
fn palette(dark: bool) -> &'static str {
if dark { DARK } else { LIGHT }
}
#[component]
fn Theme(dark: Signal<bool>, children: Children) -> impl IntoView {
// A guard: the sheet is removed when this component goes away.
let sheet = Stylesheet::install("tokens", palette(dark.get_untracked()));
let following = RenderEffect::new(move |_| {
let css = palette(dark.get());
if let Some(sheet) = sheet.as_ref() {
sheet.replace(css); // a no-op when the text is unchanged
}
});
on_cleanup_local(move || drop(following));
view! { {children.into_view_once()} }
}
const PAGE: &str = css!(
":root { background-color: var(--surface); padding: 24px }
.page { gap: 16px; align-items: flex-start }
.switch {
padding: 8px 16px;
border-radius: var(--radius);
border: 1px solid var(--border);
background-color: var(--surface-raised);
color: var(--ink);
}
.switch:hover { background-color: var(--accent); color: var(--accent-ink) }"
);
fn main() -> Result<(), zgui::Error> {
app().with_title("Theming").with_stylesheet(PAGE).run(|| {
let dark = RwSignal::new(false);
view! {
Theme(dark = dark.into()) {
column(class = "page") {
control(class = "switch", on:click = move |_| dark.set(!dark.get_untracked())) {
{move || if dark.get() { "Light" } else { "Dark" }}
}
Card(title = "Storage") {
text(class = "note") {"41 GB of 128 GB used"}
}
}
}
}
})
}Pressing the button writes one signal and replaces one sheet. No component is rebuilt, and neither
Card nor the page sheet mentions a colour.
Keep theme switches cheap
How much a switch costs depends on how many elements restyle and what each one then needs.
| Switch by | Elements restyled |
|---|---|
| class toggle | only elements affected by the class change |
| sheet replacement | the whole document is re-matched against the author rules |
| desktop colour-scheme change | the whole document, for every origin with a matching media query |
var: on a container | only the subtrees that read the changed property |
| Tokens changed | Work per restyled element |
|---|---|
| colours only | repaint; text is not reshaped |
| radius, shadow, transform | repaint, no layout |
spacing or font-size | layout, and text rebreaking or reshaping as needed |
In practice:
- Prefer a class toggle to a sheet replacement when the class can reach everything that needs it. In the frame where the set of sheets changes, the style engine's dependency filters are off.
- Prefer either to
style:declarations from a view, which cannot use those filters.
See Writing fast interfaces and Text and fonts for details.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| a property silently uses its initial value | var() names an undeclared token | check the spelling; there is no diagnostic |
| the page is themed but an open menu is not | tokens are declared on your own element, not :root | declare on :root |
Stylesheet::install returns None | called outside a window's scope | call it from a component body |
--zgui-stroke-width in em or % does nothing | only absolute lengths are read | use px and other absolute units |
| a rule stopped beating the theme sheet | the sheet was removed and re-added, moving it to the end | replace under the same name instead |
| part of a theme sheet is ignored | an invalid declaration was dropped | check the zgui::css tracing target |
Dropped declarations and rules are logged at parse time under the tracing target zgui::css, in
both debug and release builds.
Framework custom properties
| Property | Used for | Notes |
|---|---|---|
--zgui-foreground | the root element's color | set it in your theme |
--zgui-ring | the :focus-visible outline colour | set it in your theme |
--zgui-fill | vector fill | defaults to the element's color |
--zgui-stroke | vector stroke | absent means no stroke |
--zgui-stroke-width | vector stroke width | default 1px; absolute units only (px, pt, in, cm, mm, pc) |
--zgui-text-fill | painting the background through text | only accepts background |
--zgui-scrollbar-thumb | a scroll container's thumb colour | defaults to the scheme's paint |
--zgui-scrollbar-track | a scroll container's track colour | transparent by default |
--zgui-selection, --zgui-selection-text | nothing | no effect; see below |
::selection has no effect either. The selection band is drawn in the element's color at 30%
opacity, and the caret uses caret-color (by default color). To change how a selection looks,
change color.
Other --zgui-* properties control rendering effects rather than theming: --zgui-corner-shape
(Styling), and --zgui-shader, --zgui-shape, --zgui-filter and
--zgui-backdrop-filter (Custom shaders).
Next
Accessibility
Give controls roles, names and keyboard access, report state, announce changes, test what screen readers see, and look up every a11y attribute and role.
Testing
Test components and whole applications without a window — component tests, input, timers, transcripts and golden files, headless application tests, the accessibility tree and the display list.