zgui

Styling

Style elements with CSS — writing sheets with css!, style! and variants!, installing them, the cascade, state selectors, custom properties, and a reference of supported CSS.

zgui styles elements with real CSS. A view says what an element is, and a style sheet says what it looks like; class names connect the two.

Write a style sheet

A style sheet holds rules. Each rule is a selector followed by a block of declarations, and each declaration is a property and a value.

.card{ padding: 16px;background-color: #1b1e24 }
.card
The selector: which elements this rule applies to.
{ padding: 16px;
A declaration: one property and its value.
background-color: #1b1e24 }
A second declaration, then the closing brace.
The parts of a CSS rule
use zgui::prelude::*;

const SHEET: &str = css!(
    ".card { padding: 16px; border-radius: 8px; background-color: #1b1e24 }
     .card__title { font-size: 18px; font-weight: 700; color: #f2f4f8 }
     .card__note { color: #8b93a3 }"
);

#[component]
fn Card() -> impl IntoView {
    view! {
        column(class = "card") {
            label(class = "card__title") {"Storage"}
            text(class = "card__note") {"41 GB used"}
        }
    }
}

fn main() -> Result<(), zgui::Error> {
    app().with_stylesheet(SHEET).run(|| view! { Card() })
}

The view holds no colours or sizes. To change how the card looks, you change the sheet.

What css! checks

css! takes one or more string literals and returns their text as a &'static str. Several literals are joined with newlines; commas between them are optional.

It checks the text at compile time, so a broken sheet is a compile error pointing at your source. The check is structural only: brackets, quotes, comments, and blocks. It does not know property names or validate values, so zzz: 1 passes css! and is dropped at run time with a warning. The css! errors table lists every message.

CSS has no // line comments, and the parser would silently swallow the next declaration, so css! rejects //. Use /* … */, or put the remark outside the string as a Rust comment. A side effect: url(//cdn/a.css) is rejected, while https://… is fine.

css! returns the text unchanged, so a plain string or include_str! works too, without the compile-time check. See Without macros.

Scope a sheet to a component

style! declares a sheet for one component, scoped by a generated class. Write :scope for the component's root element.

style! { pub MeterStyle =>
    ":scope {
        position: relative;
        overflow: hidden;
        height: 8px;
        border-radius: 4px;
        background-color: #2a2f3a;
    }"
    ":scope > .fill {
        height: 100%;
        border-radius: inherit;
        background-color: #2b6cff;
    }"
}

It generates a type with two constants:

pub struct MeterStyle {}

impl MeterStyle {
    pub const CLASS: &'static str = "zs-3f1c90ab";  // derived from the name and the text
    pub const CSS: &'static str = /* the rules, with :scope replaced by .zs-3f1c90ab */;
}
  • The class is zs- plus an 8-digit hash of the name and the CSS. It is stable across builds and platforms, and changes when either changes.
  • Every :scope is replaced by .zs-…, except inside comments and strings.

style! installs nothing on its own. A component using it must install CSS and put CLASS on its root element; otherwise it renders unstyled, with no error.

#[component]
fn Meter(
    /// How full the bar is, from 0.0 to 1.0.
    fraction: Signal<f32>,
) -> impl IntoView {
    install_stylesheet("meter", MeterStyle::CSS);

    view! {
        box(class = MeterStyle::CLASS) {
            box(
                class = "fill",
                style:width = move || Some(format!("{}%", fraction.get() * 100.0)),
            )
        }
    }
}

Installing the same name and text again does nothing, so the call can sit in the body unconditionally: a hundred meters install one sheet.

style! declares a type, which shadows a glob-imported item of the same name. This is why the prelude exports the function app() and not a type called App.

Define variants

A component with a few visual options (tone, size, …) would otherwise build class strings by hand. variants! generates one enum per option, a stable class list, and data-* attributes for selectors.

variants! {
    /// Visual variants of a button.
    pub ButtonVariants {
        base: "btn",
        tone: { Neutral => "btn--neutral", Accent => "btn--accent" } = Neutral,
        size: { Sm => "btn--sm", Md => "" } = Md,
    }
}

This generates:

pub struct ButtonVariants { pub tone: ButtonTone, pub size: ButtonSize }

pub enum ButtonTone { Neutral, Accent }
impl ButtonTone {
    pub const fn class(self) -> &'static str;   // "btn--accent", or "" for no class
    pub const fn name(self) -> &'static str;    // "accent", for the data attribute
}

impl ButtonVariants {
    pub const BASE: &'static str = "btn";
    pub fn class_list(&self) -> String;
    pub fn classes(&self) -> Classes;
    pub fn data_attributes(&self) -> [(&'static str, &'static str); 2];
}
  • Enum names: the trailing Variants is dropped and the option name is appended, so ButtonVariants + tone gives ButtonTone.
  • Class order: BASE, then each option in declaration order, skipping empty classes.
  • Attributes: data-<option> in kebab case, with the choice name in kebab case as the value (SubOptimum → sub-optimum).
let accent = ButtonVariants { tone: ButtonTone::Accent, ..ButtonVariants::default() };

assert_eq!(accent.class_list(), "btn btn--accent");
assert_eq!(accent.data_attributes(), [("data-tone", "accent"), ("data-size", "md")]);

A complete component:

const SHEET: &str = css!(
    ".btn { padding: 8px 16px; border-radius: 8px; border: 1px solid transparent }
     .btn[data-tone=\"neutral\"] { background-color: #2a2f3a; color: #e6e9ef }
     .btn[data-tone=\"accent\"] { background-color: #2b6cff; color: #ffffff }
     .btn[data-size=\"sm\"] { padding: 4px 10px; font-size: 13px }"
);

#[component]
fn Button(
    /// The visual choices for this button.
    #[prop(optional)]
    variants: ButtonVariants,
    children: Children,
) -> impl IntoView {
    let [(_, tone), (_, size)] = variants.data_attributes();

    view! {
        control(
            class = variants.classes(),
            attr:data-tone = tone,
            attr:data-size = size,
        ) {
            {children.into_view_once()}
        }
    }
}

view! {
    Button {"Cancel"}
    Button(variants = ButtonVariants { tone: ButtonTone::Accent, size: ButtonSize::Sm }) {"Save"}
}

Selecting on data-* attributes keeps the sheet independent of how class strings are built; the classes are there when you prefer them.

classes() refers to types through the zgui crate, as view! does, so zgui must be available under that name where the macro is used.

Install sheets

For the whole application

app()
    .with_title("Storage")
    .with_stylesheet(SHEET)
    .run(|| view! { Card() })

The sheet is installed at the author origin of every window when it opens.

Each call to with_stylesheet adds one sheet. The sheets cascade in call order, so a later sheet wins at equal specificity.

WindowOptions::with_stylesheet adds a sheet to one new window, cascaded after the application sheets, so it can override shared rules for that window only.

From a view

These are in the prelude:

Prop

Type

The sheet belongs toUse
a component type, such as a button's rulesinstall_stylesheet
state, such as a theme or rules generated from dataStylesheet (removed when the guard is dropped)
// A theme sheet that goes away with this view.
let theme = Stylesheet::install("theme", ":root { --accent: #2b6cff }");

// Later, wherever the guard is held:
theme.expect("inside a window").replace(":root { --accent: #e0554b }");
  • Sheet names are shared across the whole window, so libraries should prefix theirs.
  • Called outside a window's scope, install_stylesheet does nothing (and fails a debug assertion).
  • A sheet installed while a component is being built styles that component in the same frame. It also reaches matching elements already in the document.
  • Replacing a sheet keeps its position in the cascade. Removing and re-adding it moves it to the end, where it could start winning against sheets that used to beat it.

@import is dropped in an application, because App installs no loader to resolve it. Concatenate sheets or use install_stylesheet instead.

Invalid CSS

A sheet always installs. Parts the parser cannot use are dropped and reported with tracing::warn! under the target zgui::css, in release builds too:

ProblemDropped
an unknown property or invalid valuethat declaration
an unsupported selectorthe whole rule
an unsupported at-rulethat block
:root { not-a-property: 3 }                                    /* declaration dropped */
.card:has(.title) { color: rgb(9, 0, 0) }                      /* whole rule dropped */
@container (min-width: 10px) { :root { color: rgb(8, 0, 0) } } /* at-rule dropped */
:root { color: rgb(1, 2, 3) }                                  /* applies */

The cascade

Many declarations can target the same property of the same element. The cascade picks one by comparing, in order:

  1. Origin and importance. Rules come from three origins: the framework's user-agent sheet, a user sheet, and your author sheets. For normal declarations, author beats user and user beats user agent, so your rules always beat the framework's. !important declarations rank above all normal ones, with the origin order reversed.
  2. Specificity. Computed from the selector; higher wins.
  3. Source order. The later declaration wins. A sheet installed later counts as later.

Specificity is a triple compared left to right:

PositionCountsExample
firstid selectors#main
secondclasses, attribute selectors, pseudo-classes.card, [data-tone], :hover
thirdelement names, pseudo-elementscolumn, ::before

So .card .title (0, 2, 0) beats column .title (0, 1, 1), which beats .title (0, 1, 0). One id outranks any number of classes, so avoid ids in rules you may want to override.

Inheritance

When no declaration applies, an inherited property takes the parent's value, and any other property takes its initial value.

InheritsDoes not inherit
color, font-*, line-height, letter-spacing, word-spacingpadding-*, margin-*, border-*, background-*
text-align, text-indent, word-break, overflow-wrapwidth, height, display, position, flex-*, grid-*
direction, visibility, pointer-eventsopacity, transform, filter, box-shadow, z-index
every custom property

The keywords inherit, initial, unset and revert work as in browsers. There is no quirks mode.

Default styles

zgui installs a user-agent sheet that gives each element name its default layout: row is a horizontal flex container, scroll has overflow: auto, and so on. It also sets * { box-sizing: border-box } and root font defaults. Elements shows the sheet. Any rule you write overrides it.

Style interaction states

A state is a fact about an element right now: the pointer is over it, it has focus, it is disabled. State selectors such as :hover and :disabled match them.

.button:hover { background-color: #3a7bff }
.button:disabled { opacity: 0.5 }

States the framework computes

SelectorMatches when
:hoverthe pointer is over the element
:activethe pointer is pressed on the element
:focusthe element has keyboard focus
:focus-visibleit has focus and the focus should be drawn
:focus-withinit or a descendant has focus
:enabled, :read-write, :valid, :optionalthe opposite state is not set
:dir(ltr), :dir(rtl)the computed direction

States a view sets

A view sets eight states with state:: checked, disabled, indeterminate, invalid, open, placeholder_shown, read_only and required.

control(state:disabled = move || saving.get()) {"Save"}
box(state:open = open) {"panel"}

The pairs :enabled/:disabled, :read-write/:read-only, :valid/:invalid and :optional/:required are complementary: state:disabled = false means :enabled.

Custom states

custom_state: sets a state with any name, matched by :state(name). Selection is the typical case, because CSS has no "this item is selected" pseudo-class.

control(custom_state:picked = move || chosen.get() == index) {"swatch"}
control:state(picked) { outline: 2px solid #2b6cff }

Custom properties

A custom property is a name of your own, starting with --, that holds any value. It inherits, and var(--name) reads it.

:root { --surface: #14161a; --on-surface: #f2f4f8; --pad: 12px }
.card { background-color: var(--surface); color: var(--on-surface); padding: var(--pad) }

From a view, var: sets one on an element:

column(
    class = "card",
    var:--pad = move || Some(format!("{}px", density.get())),
)

Because custom properties inherit, setting one on a container re-themes everything under it without matching any new rules. This is the recommended way to theme; see Theming.

zgui also reads a few custom properties of its own, such as --zgui-fill for vector shapes and --zgui-corner-shape for squircle corners. See Framework custom properties.

currentColor

currentColor means the element's computed color. Every colour property other than color can use it, so a border, a shadow and a text decoration can all follow one color declaration. An SVG drawn with fill="currentColor" changes colour the same way.

Keep style changes cheap

The cost of a style change depends on which properties change, not on how many rules you have.

  • Prefer class: and custom_state: to style: for values that change often. The engine skips a class or state change that no installed selector mentions; an inline declaration is always cascaded.
  • Prefer changing a custom property on a container to replacing a sheet. Replacing a sheet's text re-matches the whole document.
  • Animate opacity and transform where possible. Neither triggers layout; width, padding, font-size and similar properties do.

The cost model lists the work each kind of change causes, and The style engine explains how it works.

Debug a style

  • Dropped declarations, rules and at-rules are logged under the tracing target zgui::css. Check there first when a sheet seems to do nothing.
  • The developer tools inspector shows an element's selector, box diagram, layout values and every property that differs from its initial value.

CSS support reference

Selectors

FormExample
element namecolumn, text, control, and root for the root element
universal*
class.card
id#main (set with attr:id = "main")
attribute, all operators[data-tone], [data-tone="accent"], ^=, $=, *=, |=, ~=, with i and s flags
descendant, child.card .title, .card > label
siblingslabel + text, label ~ text
structural:root, :empty, :first-child, :last-child, :only-child, :nth-child(), :nth-of-type(), …
logical:not(), :is(), :where()
state:hover, :focus-visible, :disabled, … (see Style interaction states)
custom state:state(name)

Attribute selectors also see the id and the class list: [id] matches any element with an id, and [class*="card"] or [class~="card"] match against the classes set with class.

Unsupported selectors

FormWhat happensInstead
:has()the whole rule is droppedset a class from the view, which already knows the condition
:nth-child(An+B of S)the whole rule is droppedset a class on the rows from the list that renders them; plain :nth-child() works
::first-linethe whole rule is droppedput the lead-in in its own element
::first-letterparses, but has no effecta separate element, floated and sized
:host, ::slottednot applicable; there are no shadow trees—
:lang()always false—

For :has(), the view that renders the child conditionally can set a class on the parent in the same expression:

// Instead of `.field:has(.error) { … }`
column(class = "field", class:has-error = move || error.get().is_some()) {
    field()
    if move || error.get().is_some() {
        label(class = "error") {{move || error.get().unwrap_or_default()}}
    }
}
.field.has-error { border-color: #e0554b }

Pseudo-elements

Pseudo-elementSupportedNotes
::before, ::afteryesgenerated boxes; content is read
::selectionparsed, no effectsee below
::first-letternono first-letter box is generated
::first-linenothe rule is dropped

::before and ::after are not document nodes, so they do not affect :nth-child() or sibling selectors.

::selection has no effect. The selection highlight and caret are drawn from the element's own color: the highlight at 30 % alpha, the caret at full alpha. To restyle a selection, change the element's color. Use caret-color to change only the caret.

Properties

docs/parity.md in the zgui repository is the generated, authoritative list. It counts a property as implemented only when setting it on a test fixture visibly changes the result. At the time of writing, 178 of 250 longhands are implemented.

AreaProperties
boxdisplay, position, top/right/bottom/left and inset-*, width/height with min-/max- forms and logical forms, margin-*, padding-*, border-*-width, border-*-style, box-sizing, aspect-ratio, overflow-x/-y, float, clear, content
flexflex-direction, flex-wrap, flex-basis, flex-grow, flex-shrink, align-items, align-self, align-content, justify-content, justify-items, justify-self, row-gap, column-gap, order
gridgrid-template-columns, grid-template-rows, grid-template-areas, grid-auto-flow, grid-auto-rows, grid-auto-columns, grid-column-start/-end, grid-row-start/-end
paintingcolor, visibility, background-color, background-image, border-*-color, border-*-radius, outline-*, box-shadow, text-shadow, object-fit, object-position
compositingopacity, filter, backdrop-filter, mix-blend-mode, isolation, z-index, pointer-events, clip-path
transformstransform, translate, rotate, scale, transform-origin, perspective, transform-style, backface-visibility
textfont-* (size, family, weight, style, stretch, variation and feature settings, kerning, optical sizing, every font-variant-*), letter-spacing, word-spacing, line-height, text-align, text-indent, text-wrap-mode, white-space-collapse, tab-size, word-break, overflow-wrap, text-transform, text-overflow, text-decoration-line/-color/-style, direction
animationevery animation-* longhand except animation-composition and the scroll-driven ones; every transition-* longhand
interactioncursor, caret-color, user-select
  • cursor uses the value of the innermost element under the pointer. auto is a text cursor over editable text and an arrow elsewhere.
  • user-select: none stops the pointer from placing or dragging a text selection. It does not disable keyboard selection in an editable element.
  • linear-gradient() and radial-gradient() work as background-image values.

Properties with no effect

These are accepted without a warning and then have no effect:

AreaNot used
backgroundsbackground-position, background-size, background-repeat, background-origin, background-attachment, background-clip, background-blend-mode, border-image-*
masksevery mask-* longhand
texttext-rendering, unicode-bidi, writing-mode, line-break, text-align-last, text-justify
layoutcolumn-count, column-width, table-layout, border-collapse, border-spacing, contain, container-type, container-name
otherimage-rendering, perspective-origin, corner-*-shape, list-style-*, counter-*, quotes, will-change, animation-composition, scroll-driven animation properties

A background image always fills the box it is painted on, which is why the background-position group has no effect. For background-clip: text, use --zgui-text-fill; for corner-shape, use --zgui-corner-shape (see Framework custom properties).

Unavailable features

Some features would need a patched style engine and are deliberately out of scope:

MissingInstead
:has(), :nth-child(… of S), ::first-linesee Unsupported selectors
SVG paint properties (fill, stroke, …)--zgui-fill, --zgui-stroke, --zgui-stroke-width
text-decoration-thickness, text-underline-offset, text-underline-positiondraw the line as a border or a separate box
prefers-reduced-motiondetect the preference in Rust, set an attribute on the root, and select on it
scrollbar-gutterreserve the space with padding-right on the scrolling element

Framework custom properties

NameMeaning
--zgui-fillfill for vector shapes. Defaults to the element's color
--zgui-strokestroke for vector shapes. No stroke by default
--zgui-stroke-widthstroke width, an absolute length. Defaults to 1 CSS pixel
--zgui-text-fill: backgroundpaints the element's text with its first background-image layer (the replacement for background-clip: text)
--zgui-corner-shapecuts the corner radius as round, squircle, bevel, scoop, notch, or superellipse(<n>)
--zgui-shader, --zgui-shapeapplies a registered paint or coverage shader
--zgui-filter, --zgui-backdrop-filterapplies a registered filter shader
--zgui-foregroundthe root color in the user-agent sheet; your theme defines it
--zgui-ringthe :focus-visible outline colour; your theme defines it
--zgui-scrollbar-thumb, --zgui-scrollbar-trackthe colours of a scroll container's thumb and track

These inherit like any custom property, so --zgui-corner-shape on a card also applies to children that paint a background. Set it to none on a subtree to opt out. Where the framework reads a custom property as a length, it accepts absolute units only (px, in, cm, mm, pt, pc). Custom shaders and corner shapes covers the shader properties and their parameters.

Colours

All CSS colour functions work, including rgb(), hsl(), hwb(), lab(), lch(), oklab(), oklch() and color() with display-p3, rec2020 and the other predefined spaces. A colour keeps the space it was written in until it is drawn, so gradients between wide-gamut colours do not band.

Units

UnitRelative to
pxone CSS pixel. Everything you write is in CSS pixels, including with_size
in, cm, mm, pt, pc96 CSS pixels per inch
emthe element's font-size
rem, rlh, rex, rch, ricthe root element's font metrics
%whatever the property defines
vw, vhthe window size
calc()any mix of the above, including var()

A CSS pixel is not a device pixel; the window's scale factor converts between them. See Layout.

Media queries

A media query applies rules only when a condition about the window holds:

@media (min-width: 768px) {
    .sidebar { display: block }
}

@media (prefers-color-scheme: dark) {
    :root { --surface: #14161a; --on-surface: #f2f4f8 }
}
FeatureAnswer
width, height and their min-/max- formsthe window size, in CSS pixels
aspect-ratiothe window's
resolutionthe scale factor
prefers-color-schemethe colour scheme the platform reports, updated while the program runs
pointer, any-pointerfine
hover, any-hoverhover

The media type is always screen. prefers-reduced-motion, prefers-contrast and forced-colors are not available. For choosing light or dark from inside the app, see Theming.

Not built yet· @container is not supported yet; the whole block is dropped. Use a media query for decisions based on the window size, or a class the view sets from a measured size.

css! errors

ProblemMessage
/* with no */this comment is never closed
// used as a comment`//` is not a comment in CSS
a string with no closing quotethis string is never closed
) or ] with no opener`)` closes something that was never opened
( or [ never closedthis is never closed
{ with no selector before itthis block has no selector
} with no opener`}` closes a block that was never opened
{ never closedthis block is never closed
a declaration with no colon`<segment>` is not a declaration

Each message includes the line and column inside the CSS.

Next

On this page