Elements
The sixteen built-in elements — what each is for, the layout it starts with, and which attributes it accepts.
Elements are the building blocks of every view: containers, text, images, inputs. zgui has sixteen of them, each a box you can style, listen to, and fill with children. Each starts with a default layout that your style sheet can change.
Coming from HTML
The element names describe parts of an application interface, not parts of a document:
- There is no
div. A container with no particular meaning isbox. - There is no
span.textis a run of prose, andlabelis text that names something else. - There is no
input.fieldis one value the user enters,editoris text the user edits, andcontrolis anything the user operates.
The set is closed. To add a widget with its own layout and painting, implement a
CustomElement. To use different element names, see
Define your own elements.
All elements
| Name | Meaning | Default layout |
|---|---|---|
box | a container with no particular meaning | display: block |
row | children in a line, left to right | display: flex; flex-direction: row |
column | children in a line, top to bottom | display: flex; flex-direction: column |
stack | children over one another (see Containers) | display: flex; flex-direction: column |
text | a run of text | display: inline |
label | text that names something else | display: inline |
image | a picture, sized by its pixels | display: inline-block |
vector | shapes drawn from paths or an SVG document | display: inline-block |
canvas | shapes that Rust code draws | display: inline-block; width: 300px; height: 150px |
scroll | content that can be larger than its box | display: block; overflow: auto |
editor | multi-line text the user edits | display: block |
field | one value the user enters | display: block |
control | something the user operates: a button, a switch, a slider thumb | display: block |
surface | pixels produced by your own wgpu renderer | display: inline-block |
spacer | takes up the leftover space | display: block; flex: 1 1 auto |
overlay_root | where portalled content goes (one per window) | position: fixed, covering the window |
The default layout comes from zgui's built-in style sheet. Any rule you write overrides it, so
column { flex-direction: row } works. Default styles shows the sheet.
Containers
box, row, column, stack and spacer place other things.
use zgui::prelude::*;
const SHEET: &str = css!(
".card { gap: 8px; padding: 16px; border-radius: 12px; background-color: #191d26; }
.card__row { align-items: center; gap: 8px; }
.card__value { color: #7d879b; }
.card__note { padding-top: 8px; border-top: 1px solid #262b36; }"
);
view! {
column(class = "card") {
label(class = "card__title") {"Storage"}
row(class = "card__row") {
text {"Used"}
spacer()
text(class = "card__value") {"41 GB"}
}
box(class = "card__note") {
text {"Last checked an hour ago."}
}
}
}rowandcolumnare already flex containers. Write only the properties you want to change:gap,align-items,justify-content,flex-wrap.boxis a block. Its children stack vertically and fill the width, andgaphas no effect on it.spacerabsorbs the free space in a flex container, pushing what follows it to the far end. In a block container it does nothing.
Partial· stack is meant to place its children over one another, but today
it gets the same rule as column. Position the children yourself:
.stack { position: relative; }
.stack > * { position: absolute; inset: 0; }Text
text and label are inline. A string literal is already a text child, so both just hold the
string.
view! {
column(class = "field-row") {
label(class = "field-row__name") {"Display name"}
text(class = "field-row__value") {"Ada Lovelace"}
}
}Use text for prose and values, and label for captions and titles. The difference is for your
style sheet and for readers of the code: assistive technology does not treat a label
differently. An element's meaning to assistive technology comes from a11y: attributes, covered in
Accessibility.
Images and drawings
image
view! {
image(src = "avatar.png", a11y:label = "Ada Lovelace")
}src names a local file. zgui decodes PNG, JPEG, WebP and GIF off the UI thread. The picture's
pixel size becomes its natural size in CSS pixels, which CSS can override; object-fit and
object-position control how the picture fills the box. A reactive src changes the picture.
alt is an ordinary attribute. Use a11y:label for the accessible name.
Images covers memory sources, decode limits and caching.
vector
vector draws outlines: one path per line, written in SVG path notation.
view! {
vector(
class = "icon",
prop:viewBox = "0 0 24 24",
prop:d = "M20.5 7.1 L18.9 5.5 L9.6 14.8 L5.1 10.3 L3.5 11.9 L9.6 18.0 Z",
)
}With a viewBox, the outlines are scaled uniformly to fit the content box and centred, so one path
draws at any icon size. Without one, the outlines are in CSS pixels from the content box's top-left
corner, which suits chart marks.
The builder methods take typed values instead of strings. kurbo is re-exported at
zgui::elements::kurbo:
use zgui::elements::kurbo::{Rect, Shape};
use zgui::elements::vector;
let square = Rect::new(0.0, 0.0, 16.0, 16.0).to_path(0.1);
let drawing = vector().paths([square]).view_box(0.0, 0.0, 16.0, 16.0);You can also pass a whole SVG document. It replaces paths and view_box, because it brings its
own coordinate space:
let icon = vector().document(
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path d="M2 8 L8 2 L14 8 L8 14 Z" fill="currentColor"/>
</svg>"#,
);fill="currentColor" takes the element's computed color, so one asset can be dark on a light
button and light on a dark one. Colours written in the document are kept as they are.
Paint comes from three inherited custom properties, so setting one on an ancestor themes every drawing below it:
| Property | Default |
|---|---|
--zgui-fill | the element's computed color |
--zgui-stroke | none; outlines are not stroked |
--zgui-stroke-width | 1 |
fill: red in a style sheet does nothing: the SVG paint properties are not available in this
build and are dropped when the sheet is parsed. Write --zgui-fill: red, or set color.
canvas
canvas is the imperative counterpart to vector: Rust code pushes shapes into a retained scene,
drawn through the same vector pipeline.
.draw(|cx| ...)re-runs a closure when the signals it reads or the element's size change..scene(&handle)shows aCanvasHandlethat event handlers mutate.CanvasHandle::set_transformpans and zooms the scene without rebuilding it.
An unstyled canvas is 300 × 150 CSS pixels. Vector and canvas covers both forms.
Interactive elements
control
control is anything the user operates, such as a button. It is focusable by default and handles
presses and keys before you add any listener:
#[component]
fn Toggle() -> impl IntoView {
let (on, set_on) = signal(false);
view! {
control(
class = "toggle",
a11y:role = Role::Button,
state:checked = on,
on:click = move |_| set_on.update(|value| *value = !*value),
) {
{move || if on.get() { "On" } else { "Off" }}
}
}
}| Input | Default behaviour |
|---|---|
| a press | focus moves to the nearest focusable element under the pointer; pressing something unfocusable clears focus |
| a primary-button release over the pressed element | activates it. Sliding off before releasing cancels; other buttons never activate |
| Enter or Space | activates the focused element. Key repeats are ignored |
| activation | delivers a click event to the element |
The keyboard rule applies to any focused element, not just control. A control has no role and
no appearance of its own: set the role with a11y:role and the look with CSS. A listener can cancel
each default; see Events.
field and editor
field is one value the user enters, and editor is text the user edits. Both get a full editing
model the first time a key or input method reaches them:
- typing, Backspace and Delete;
- arrow keys, Home and End, with Shift to extend the selection;
- undo and redo;
- input-method composition;
- clipboard copy, cut and paste;
- caret placement and drag selection with the pointer.
The caret and selection are drawn in the element's computed color.
The only difference between the two: editor accepts line breaks. In a field, Enter
is left to the surrounding code, so a form can submit on it.
view! {
field(class = "field", a11y:role = Role::TextInput) {"Ada"}
}The text child is the initial value. Do not rewrite it later: that node is the text the editing model types into.
Editing is a default action. It runs after every listener on the event's path, unless one of
them calls prevent_default. A numeric-only field is a field whose on:key_down handler
prevents the keys it rejects.
value and placeholder attributes are not connected to the
editing model yet.
| Attribute | What it does today |
|---|---|
disabled = … | sets :disabled, which removes the element from the focus order, from pointer input and from editing |
value = … | writes a value property that the editing model does not read |
placeholder = … | writes a placeholder attribute that nothing renders |
To set a field's text from your own state, call NodeRef::set_value, covered in
Effects and lifecycle. For a placeholder, generate one with
::before and select the empty case with :empty.
Other elements
scroll
scroll is display: block; overflow: auto. Scrolling depends on the used overflow, not on the
element name, so any element with overflow: auto or scroll scrolls. scroll just has it by
default.
const SHEET: &str = css!(".log { height: 240px; } .log__lines { gap: 4px; }");
view! {
scroll(class = "log") {
column(class = "log__lines") {
text {"one"}
text {"two"}
text {"three"}
}
}
}A wheel or trackpad gesture scrolls the nearest scrolling ancestor of the element under the pointer. When that container reaches its end, the rest of the gesture goes to the next scrolling ancestor. Scrolling covers offsets, scrollbars, momentum and programmatic scrolling.
surface
surface shows pixels from your own wgpu renderer. Bind a SurfaceRenderer when zgui should drive
the rendering, or a SurfaceHandle when your producer runs on its own thread or schedule. CSS
supplies the box and applies clipping, transforms and opacity. GPU surfaces
covers both models.
image and surface are the only replaced elements: their children are never laid out or painted.
Every other element, including canvas and vector, lays out its children.
overlay_root
An overlay is content that must escape the box it is written in: a menu that must not be clipped by a scrolling ancestor, a dialog that paints over everything.
zgui creates one overlay_root per window, with four layer children (content, popover, modal,
toast) that stack in a fixed order.
Do not write overlay_root() in a view; every window already has one. Use Portal to put content
on a layer, as shown in Control flow.
Focus and tabindex
control, field and editor are focusable by default. Any other element needs tabindex, which
takes a Focus value (exported by the prelude):
| Value | Means |
|---|---|
Focus::Sequential | reachable with Tab, in document order |
Focus::Programmatic | focusable only by code, for example NodeRef::focus |
There is no integer tab order: a hand-numbered order is hard to keep consistent and is almost always worse than document order.
An element can take focus when it is an element (not a text node), is not :disabled, declares
tabindex or is one of the three focusable names, and generates a visible box.
tabindex can follow state. This is how a disabled control leaves the tab order, or how a
composite widget moves its single tab stop between items:
control(tabindex = move || {
if disabled.get() { Focus::Programmatic } else { Focus::Sequential }
})The built-in sheet draws the focus ring with :focus-visible and --zgui-ring. Define
--zgui-ring in your theme, or the ring has no colour.
A raw integer written with attr:tabindex is still honoured: positive values come first in
increasing order, negative values are focusable but skipped by Tab, and a value that
does not parse is ignored. Keyboard and focus covers
traversal in full.
Which attributes each element takes
Each element name is a Rust function that returns a typed builder, and the type decides which attributes the element accepts. Attributes explains each form.
Universal attributes
Every element accepts these, including elements you define yourself.
| In a view | Builder method | Sets |
|---|---|---|
class = v | .class(impl Into<Classes>) | classes merged into the class list. Not reactive |
class:name = v | .class_toggle(ClassName, bool) | one class on or off |
style = v | .style_text(Option<String>) | the whole inline style text |
style:gap = v | .style_property(impl Into<String>, Option<String>) | one inline declaration |
var:--brand = v | .custom_property(CustomPropertyName, Option<String>) | one custom property |
attr:data-x = v | .attribute(AttrName, Option<String>) | one attribute that selectors can match |
state:disabled = v | .state(UiState, bool) | one of the eight states a view may set |
custom_state:picked = v | .custom_state(Ident, bool) | a state of your own, matched by :state(picked) |
prop:key = v | .property(PropKey, PropValue) | a property the element reads; invisible to selectors |
on:click = h | .on(E, handler) | a listener |
on:click:capture = h | .on_with(E, ListenerOptions, handler) | a listener with options |
a11y:label = v | .a11y(A11yBinding) | accessibility information |
node_ref = h | .node_ref(NodeRef) | fills the handle once the node exists |
tabindex = v | .tabindex(Focus) | makes the element focusable |
hidden = v | .hidden(bool) | writes hidden, which the built-in sheet turns into display: none |
{..bundle} | .attrs(Attrs) | replays a forwarded bundle |
Apart from class, node_ref, listeners and the spread, every value can be a constant, a signal,
or a closure. A constant is written once; a signal or closure keeps the value up to date. See
Reactivity in views.
style = … replaces the element's whole inline style, including declarations set with
style:. Don't mix the two on one element.
There is no id method. Write attr:id = "main", which #main selectors match.
Element-specific attributes
| Element | Attributes beyond the universal set |
|---|---|
box, row, column, stack, text, label, scroll, spacer, overlay_root | none |
image | src, alt |
vector | paths, document, view_box, hit_shape, fill, stroke, stroke_width |
canvas | scene, view_box, draw |
surface | source, renderer (through SurfaceElementExt) |
field, editor | value, placeholder, disabled |
control | disabled |
There is no checked, open, read_only or required method. Those are states: write
state:checked, state:open, and so on.
An attribute on the wrong element is a compile error:
row().src("picture.png"); // a row has no source
row().placeholder("Search"); // nothing is entered into a row
text().disabled(true); // text is not operatedNotes on vector:
view_boxtakes four numbers, which thename = valuesyntax cannot express. In a view, writeprop:viewBox = "0 0 24 24".paths,document,view_boxandhit_shapeare written once. To change a drawing with state, setprop:dfrom a closure.fill,strokeandstroke_widthset the--zgui-*paint properties and may be reactive.- Not built yet·
hit_shapeis stored but not read yet. The whole box is the hit area.
Build an element without view!
view! is shorthand for these builders, and you can call them directly. Each method takes the
element and returns it. Nothing is created until the view is built, so an Element<T> can be
stored, passed and returned like any value. Without macros maps
every view! form to its builder call.
use zgui::prelude::*;
use zgui::elements::control;
/// A button, without `view!`.
fn button(caption: &'static str, press: impl Fn() + 'static) -> impl IntoView {
control()
.class("button")
.a11y(A11yBinding::new(Role::Button))
.on(events::CLICK, move |_| press())
.child(caption)
}
// A built element is a value, so it can be a braced child.
view! {
row(class = "actions") {
{button("Cancel", move || dismiss.set(true))}
{button("Save", move || save.set(true))}
}
}The element functions are not in the prelude, to keep sixteen short names out of your namespace.
Import them from zgui::elements. box is a keyword, so its function is r#box.
| Method | Adds |
|---|---|
.child(impl IntoView) | one child, after the existing ones |
.children(impl IntoIterator<Item = AnyView>) | every child of an iterator, in order |
use zgui::elements::{label, row};
fn chips(names: Vec<String>) -> impl IntoView {
row().class("chips").children(
names
.into_iter()
.map(|name| AnyView::new(label().class("chip").child(name))),
)
}A listener closure stored in a variable before it reaches .on(…) fails to compile with
implementation of Fn is not general enough. Build it with handler, which names the event up
front:
let pick = handler(events::CLICK, move |_| { /* … */ });
let button = control().on(events::CLICK, pick);A closure written inline at on: or .on(…) does not need this.
Define your own elements
To use element names of your own, for example to build a different document language, implement
Tag on a marker type. The name it returns is what selectors match:
use zgui::elements::{Element, Tag};
use zgui::view::ElementName;
/// One name from a document language of your own.
pub struct Div;
impl Tag for Div {
fn name() -> ElementName {
ElementName::new("div")
}
}
/// The function a view calls.
pub fn div() -> Element<Div> {
Element::new()
}A view reaches it by path. The case of the last segment decides element versus component:
view! {
html::div(class = "page") {
html::span() {"hello"}
}
}Your elements get every universal attribute, the whole view! grammar, the cascade, hit testing
and event dispatch. They do not get:
| Missing | What to do |
|---|---|
| Layout defaults. No rule in the built-in sheet matches the name, so it lays out as inline. | Install a sheet that gives your names their display. |
Default focusability. Only control, field and editor are focusable by name. | Write tabindex on elements that take focus. |
Editing. Only field and editor get the editing model. | — |
Typed attributes. src, value, disabled and the other typed attributes only exist on the built-in names. | Write attr:src, prop:value or state:disabled instead. |
Default styles
zgui installs a built-in style sheet (the user-agent sheet) below every sheet of yours. Any rule you
write beats it; Styling explains the cascade. The relevant part, from
crates/zgui-style/src/sheets/ua.rs:
* { box-sizing: border-box; }
:root {
display: block;
width: 100%;
height: 100%;
font-family: system-ui, sans-serif;
font-size: 16px;
line-height: 1.5;
color: var(--zgui-foreground);
}
box, field, control, editor { display: block; }
row { display: flex; flex-direction: row; }
column, stack { display: flex; flex-direction: column; }
text, label { display: inline; }
image, canvas, vector, surface { display: inline-block; }
canvas { width: 300px; height: 150px; }
scroll { display: block; overflow: auto; }
spacer { display: block; flex: 1 1 auto; }
:focus-visible { outline: 2px solid var(--zgui-ring); outline-offset: 2px; }
:disabled { pointer-events: none; }
[hidden] { display: none; }The sheet also positions overlay_root and its four layers; see
Overlays and portals.
The --zgui-* colours are referenced but not defined. Your theme defines them; without a theme
there is no focus-ring colour. See Theming.