Text and fonts
Show text, control wrapping, truncation and white space, align icons with text, register your own fonts, and see which style changes reshape text.
zgui lays out and draws text itself, using the CSS text properties you already know. You choose
fonts with font-family and register any faces you ship with Fonts.
Show text
use zgui::prelude::*;
view! {
column(class = "card") {
label(class = "card__title") {"Storage"}
text(class = "card__body") {"Everything written to disk since installation."}
}
}The framework style sheet gives both elements the same rule, text, label { display: inline; },
and nothing else treats them differently. Pick by meaning:
| Element | Use for |
|---|---|
text | prose, values, messages |
label | words that name something else: a field caption, a control title, a heading |
label gets no accessibility role automatically. Set a11y:role and a11y:labelled_by yourself;
see Accessibility.
A string literal is already a text node: column {"41 GB"} works. Wrap it in text or label only
when you need a selector, a class, or a listener.
Paragraphs
A paragraph is a run of inline content laid out together: one string, one set of lines. The parent decides where paragraphs start and end:
- In a block container (
box,control,field,editor,scroll), adjacent inline children form one paragraph and share lines. - In a flex or grid container (
row,column,stack), every child is a separate block-level item and its own paragraph.
view! {
box {
text {"Used "} // one paragraph: "Used 41 GB"
text {"41 GB"}
}
column {
text {"Used"} // two paragraphs, stacked
text {"41 GB"}
}
}text-align and text-indent apply to the block that holds the paragraph, not to the inline
text element. Put text-align: center on the box, not on the text.
Control wrapping
.tight { text-wrap-mode: nowrap; } /* only forced breaks end a line */
.cjk { word-break: break-all; } /* break between any two characters */
.urls { overflow-wrap: break-word; } /* break a long word only if it would overflow */word-break changes where breaks are allowed. overflow-wrap only applies when a word does not fit
otherwise. They combine.
By default (overflow-wrap: normal) a word longer than its line is not broken. It overflows the
block, and the block's overflow decides whether the overflow is visible.
| Declaration | A 400 px word in a 200 px block |
|---|---|
| none | one 400 px line, overflowing |
overflow-wrap: break-word | broken at 200 px |
overflow-wrap: anywhere | broken, and the block's min-content width drops to one character |
word-break: break-all | broken, and every other word may break too |
The difference between break-word and anywhere matters for content-sized flex and grid tracks:
anywhere lets the track shrink to one character, while break-word keeps it at least as wide as
the longest word.
nowrap also holds when the line contains inline boxes such as icons or images: the line stays
whole and overflows rather than breaking next to a box.
Truncate a line with an ellipsis
.path {
text-wrap-mode: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}zgui removes whole clusters until the mark fits, then draws it at the cut, so a ligature is never cut
in half. clip draws no mark, and a quoted string draws that string. With two values, the first is
the left side and the second the right. text-overflow does nothing while inline overflow is
visible.
Preserve white space
white-space | Spaces | Newlines | Soft wrapping |
|---|---|---|---|
normal | collapse | collapse | yes |
pre | preserved | break | no |
pre-wrap | preserved | break | yes |
pre-line | collapse | break | yes |
nowrap | collapse | collapse | no |
The shorthand sets white-space-collapse and text-wrap-mode. Use the longhands to set one without
the other. When collapsing, white space at the start of a paragraph or after a forced break is
removed:
" leading" -> "leading"
"trailing " -> "trailing"
"a \n\t b" -> "a b"tab-size only affects a tab that survives white-space collapsing. Under the default
white-space-collapse: collapse a tab becomes one space. Set white-space: pre (or pre-wrap)
first.
Align an icon with text
In a row, both children are flex items. Align their first baselines:
view! {
row(class = "field") {
vector(class = "field__icon", prop:svg = ICON)
text {"Saved to disk"}
}
}.field { align-items: baseline; gap: 8px; }Inside a block, the icon is inline. Use vertical-align:
| Value | Placement |
|---|---|
baseline | its baseline on the line's baseline |
middle | its midpoint at the baseline plus half the parent's x-height |
text-top, text-bottom | aligned to the top or bottom of the parent's content area |
super, sub | raised by 0.34 or lowered by 0.20 of the font size |
| a length | raised by that length |
top, bottom | aligned to the line box edge (costs a second line-breaking pass for that line) |
Line metrics explains baselines and line boxes.
Example: a text panel
use zgui::prelude::*;
#[component]
fn Article() -> impl IntoView {
view! {
column(class = "article") {
label(class = "article__heading") {"Storage"}
text(class = "article__body") {
"Everything this application has written to disk since it was installed, \
including caches it will regenerate and downloads it will not."
}
box(class = "article__path") {
text {"/home/user/.local/share/example/cache/objects/9f2c1a4b"}
}
}
}
}
const SHEET: &str = css!(
":root {
background-color: #0b0d12;
color: #e9edf6;
font-family: system-ui, sans-serif;
}
.article { gap: 8px; padding: 20px 24px; max-width: 380px; }
.article__heading {
font-size: 20px;
font-weight: 650;
line-height: 1.2;
letter-spacing: -0.2px;
}
.article__body {
font-size: 14px;
line-height: 1.55;
color: #8a93a6;
overflow-wrap: break-word;
}
.article__path {
font-family: monospace;
font-size: 12px;
color: #6c7488;
text-wrap-mode: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}"
);.articleis a flex column, so each child is its own paragraph.- The heading's
line-height: 1.2is tighter than most faces, giving negative leading. - The body wraps inside 380 px;
overflow-wrap: break-wordbreaks only words that would overflow. - The path stays on one line and ends in an ellipsis. It is a block, so
overflowapplies to it.
Resizing the window rebreaks the body and nothing else. Changing the palette reshapes nothing.
Use your own fonts
One Fonts value holds every face the application draws with. Register a font file once and it is
available everywhere: in style resolution, shaping and drawing.
use std::sync::Arc;
use zgui::prelude::*;
fn main() -> Result<(), zgui::Error> {
let fonts = Fonts::shipped_only();
fonts
.register(Arc::new(*include_bytes!("../fonts/Inter-Regular.ttf")), Some("Inter"))
.expect("the shipped face");
app()
.with_fonts(fonts)
.with_stylesheet(SHEET)
.run(|| view! { Article() })
}Then refer to the family by name in CSS, for example font-family: Inter, sans-serif.
@font-face in a style sheet registers nothing. Fonts::register is the only way to add a face.
| API | What it does |
|---|---|
Fonts::system() | installed faces plus registered ones (the default) |
Fonts::shipped_only() | registered faces only |
fonts.register(data, family) | adds every face in a font file; family renames them, None keeps the file's own family name |
App::with_fonts(fonts) | replaces the application's collection |
App::fonts() | borrows the current collection (creating Fonts::system() if none was set), e.g. to register one extra face |
fonts.shaper() | a Shaper for custom single-line layout |
fonts.metrics(), fonts.raster() | the metric source and glyph rasteriser over these faces |
Fonts is in the prelude and is a cheap, cloneable handle. It is provided as context before
App::with_context runs, so components can use use_context::<Fonts>().
data is a FontData (Arc<dyn AsRef<[u8]> + Send + Sync>): Arc::new(std::fs::read(path)?) and
Arc::new(*include_bytes!("…")) both work. register returns FontError::Unrecognised,
Malformed, or Empty when the bytes are not a usable font.
A FaceId stays valid for the life of its Fonts collection and is never reused. IDs from
different collections are unrelated.
For custom elements, Shaper::shape_line takes a LineRequest and returns owned glyph runs you can
cache and draw with ScenePainter::glyphs. See
Custom elements.
System or shipped fonts
system() | shipped_only() | |
|---|---|---|
| Faces | operating system plus registered | registered only |
| Same pixels on every machine | no | yes |
| Generic families | from the system configuration | the first registered family fills every unclaimed generic |
| No registrations | system faces | no text at all |
Use shipped_only() for screenshot tests and reference images, and system() otherwise.
Faster font resolution
The zgui repository patches fontique (the font collection under parley 0.11.1) to resolve fonts
faster. A crates.io build gets the unpatched release, which draws the same text but resolves fonts
more slowly. To use the patched copy, add to your Cargo.toml:
[patch.crates-io]
fontique = { git = "https://github.com/zortax/zgui", tag = "v0.1.0" }Font fallback and synthesis
A character the selected face cannot draw is resolved again, per character, by script. A Latin
sentence with one Arabic word or one emoji is drawn with two faces. With Fonts::system() the
operating system's fallback list is used. With Fonts::shipped_only() the registered families are
tried instead.
If a family has no face for the requested weight, zgui thickens the nearest face. If it has no
italic or oblique face, font-style: italic draws the upright face sheared forward.
What causes reshaping
Turning a string into positioned glyphs (shaping) is the expensive step in drawing text. Splitting shaped glyphs into lines at a given width (breaking) is cheap. A shaped paragraph is cached across frames, so a style change costs either a reshape, a rebreak, or nothing:
| Change | Cost |
|---|---|
| the string | reshape |
font-*, font-variant-*, font-feature-settings, font-variation-settings | reshape |
line-height, letter-spacing, word-spacing | reshape |
word-break, white-space-collapse, text-transform, direction | reshape |
| moving to a display with a different scale factor | reshape |
| an inline box (icon, image) changing width | reshape; a width seen before reuses its cached shape |
| the available width | rebreak only |
text-align, text-indent, overflow-wrap, text-wrap-mode, text-overflow, vertical-align | rebreak only |
background-color, border-*, opacity, transform | neither |
Avoid animating properties that reshape. Theme changes do not reshape: each run draws its colour through a paint slot, and changing token values rewrites the slot and leaves shaped text valid. A run that starts drawing through a different slot is shaped once for it, and both results stay cached. See Caches and the text engine for how this works.
Line metrics
Text sits on a baseline. Every line has a line box with a height and a baseline inside it.
The face declares an ascent and descent. The difference between line-height and ascent + descent
is the leading, split above and below. A line-height smaller than the face's natural height
gives negative leading: the line box is shorter than the glyphs, which overhang it above and
below, as in browsers.
Every line box is at least as tall as the strut, an invisible box with the block's own font metrics. It keeps empty lines, and lines that hold only a small icon, from collapsing.
Font-relative units
ex, ch, cap and ic come from the face the element's own style selects. If the face lacks a
metric, a fallback is used instead of zero.
| Unit | Metric | Fallback |
|---|---|---|
ex | x-height | half the font size |
ch | advance of 0 | half the font size |
cap | cap height | the face's ascent |
ic | advance of 水 | the font size |
Supported properties
| Property | Notes |
|---|---|
font-family | families in order, ending in a generic: serif, sans-serif, monospace, cursive, fantasy, system-ui |
font-size | |
font-weight | 1–1000. Missing weights are synthesised |
font-style | normal, italic, oblique <angle>. Missing italics are synthesised |
font-stretch | matched against the face's width axis |
font-variation-settings | variable-font axes by tag |
font-optical-sizing | auto drives opsz from the font size |
font-feature-settings | OpenType features by tag; overrides features implied by the properties below |
font-kerning | normal, none |
font-variant-ligatures, -caps, -numeric, -position, -east-asian | mapped to OpenType features |
line-height | normal uses the face's spacing; a number multiplies the font size; a length is used as-is |
letter-spacing | extra advance per cluster; % is of the font size |
word-spacing | extra advance per space; % is of a space's advance |
word-break | normal, break-all, keep-all |
overflow-wrap | normal, break-word, anywhere |
text-wrap-mode | wrap, nowrap |
white-space-collapse | collapse, preserve, preserve-breaks, break-spaces |
white-space | shorthand: normal, pre, pre-line, pre-wrap, nowrap |
tab-size | only affects preserved tabs |
text-transform | uppercase, lowercase, capitalize, plus full-width, full-size-kana |
text-overflow | clip, ellipsis, or a string; one or two values |
text-align | start, end, left, right, center, justify |
text-indent | with hanging and each-line |
direction | ltr, rtl |
color | |
caret-color | caret in field and editor; auto uses color |
text-decoration-line, -color, -style | solid, double, dotted, dashed, wavy |
text-shadow | offset, blur, colour |
vertical-align | see Align an icon with text |
Unsupported properties
These parse and cascade, but nothing acts on the value: text-align-last, text-justify,
line-break, writing-mode (no vertical text), font-synthesis-weight (missing weights are always
synthesised), font-language-override (set the document language instead), unicode-bidi (set
direction on the block), text-rendering, -webkit-text-security.
text-decoration-thickness, text-underline-offset and text-underline-position are not parsed at
all; the declaration is dropped. Decoration lines are one CSS pixel thick. Use a border for a
heavier rule.
Glyph rendering
| Path | When |
|---|---|
| Atlas | Up to 96 CSS px (capped at 256 device px), translation-only transform, one-colour brush, or any colour-glyph face such as emoji |
| Outline | Everything else: large display sizes, rotation or scale, gradient brushes |
Almost all body text takes the atlas path, which is the only hinted path. Large, rotated, scaled or gradient-filled text is drawn from unhinted outlines.
Next
Error handling
Show errors in the interface with Result and ErrorBoundary, handle start-up errors, avoid panics, and find failures that only appear in logs.
Keyboard and focus
Make elements focusable, style focus, add shortcuts, move focus from code, trap focus in a dialog, and handle keys in text fields.