zgui

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:

ElementUse for
textprose, values, messages
labelwords 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.

DeclarationA 400 px word in a 200 px block
noneone 400 px line, overflowing
overflow-wrap: break-wordbroken at 200 px
overflow-wrap: anywherebroken, and the block's min-content width drops to one character
word-break: break-allbroken, 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-spaceSpacesNewlinesSoft wrapping
normalcollapsecollapseyes
prepreservedbreakno
pre-wrappreservedbreakyes
pre-linecollapsebreakyes
nowrapcollapsecollapseno

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:

ValuePlacement
baselineits baseline on the line's baseline
middleits midpoint at the baseline plus half the parent's x-height
text-top, text-bottomaligned to the top or bottom of the parent's content area
super, subraised by 0.34 or lowered by 0.20 of the font size
a lengthraised by that length
top, bottomaligned 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;
    }"
);
  • .article is a flex column, so each child is its own paragraph.
  • The heading's line-height: 1.2 is tighter than most faces, giving negative leading.
  • The body wraps inside 380 px; overflow-wrap: break-word breaks only words that would overflow.
  • The path stays on one line and ends in an ellipsis. It is a block, so overflow applies 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.

APIWhat 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()
Facesoperating system plus registeredregistered only
Same pixels on every machinenoyes
Generic familiesfrom the system configurationthe first registered family fills every unclaimed generic
No registrationssystem facesno 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:

ChangeCost
the stringreshape
font-*, font-variant-*, font-feature-settings, font-variation-settingsreshape
line-height, letter-spacing, word-spacingreshape
word-break, white-space-collapse, text-transform, directionreshape
moving to a display with a different scale factorreshape
an inline box (icon, image) changing widthreshape; a width seen before reuses its cached shape
the available widthrebreak only
text-align, text-indent, overflow-wrap, text-wrap-mode, text-overflow, vertical-alignrebreak only
background-color, border-*, opacity, transformneither

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.

Half the leading
Line box top
Hello, typography
Face ascent
Baseline
Face descent
Half the leading
Line box bottom
How a line box is divided around its baseline

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.

UnitMetricFallback
exx-heighthalf the font size
chadvance of 0half the font size
capcap heightthe face's ascent
icadvance of 水the font size

Supported properties

PropertyNotes
font-familyfamilies in order, ending in a generic: serif, sans-serif, monospace, cursive, fantasy, system-ui
font-size
font-weight1–1000. Missing weights are synthesised
font-stylenormal, italic, oblique <angle>. Missing italics are synthesised
font-stretchmatched against the face's width axis
font-variation-settingsvariable-font axes by tag
font-optical-sizingauto drives opsz from the font size
font-feature-settingsOpenType features by tag; overrides features implied by the properties below
font-kerningnormal, none
font-variant-ligatures, -caps, -numeric, -position, -east-asianmapped to OpenType features
line-heightnormal uses the face's spacing; a number multiplies the font size; a length is used as-is
letter-spacingextra advance per cluster; % is of the font size
word-spacingextra advance per space; % is of a space's advance
word-breaknormal, break-all, keep-all
overflow-wrapnormal, break-word, anywhere
text-wrap-modewrap, nowrap
white-space-collapsecollapse, preserve, preserve-breaks, break-spaces
white-spaceshorthand: normal, pre, pre-line, pre-wrap, nowrap
tab-sizeonly affects preserved tabs
text-transformuppercase, lowercase, capitalize, plus full-width, full-size-kana
text-overflowclip, ellipsis, or a string; one or two values
text-alignstart, end, left, right, center, justify
text-indentwith hanging and each-line
directionltr, rtl
color
caret-colorcaret in field and editor; auto uses color
text-decoration-line, -color, -stylesolid, double, dotted, dashed, wavy
text-shadowoffset, blur, colour
vertical-alignsee 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

PathWhen
AtlasUp to 96 CSS px (capped at 256 device px), translation-only transform, one-colour brush, or any colour-glyph face such as emoji
OutlineEverything 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

On this page