Layout
An interface is laid out by nesting containers. A container arranges its children in one direction or layers them on top of each other, with configurable padding, spacing and alignment. Each child sets its own size: it fits its content, takes the remaining space, or has a fixed size.
All settings are chained methods. Lengths are in logical pixels and accept integers or floats.
1. Containers and direction
Section titled “1. Containers and direction”Create a container with a method on ui, chain its settings, and declare its children in
children:
use cpui::Ui;
fn header(ui: &mut Ui<'_>) { ui.row().w_fill().px(16).py(8).gap(8).children(|ui| { ui.heading("Files"); ui.spacer(); ui.button("New").primary(); ui.button("Open"); });}| Container | Direction | Across the direction |
|---|---|---|
ui.row() |
Left to right | Centered |
ui.column() |
Top to bottom | Start (left) |
ui.flow() |
Left to right, wrapping when a row is full | Centered |
ui.grid(min_column_width) |
Equal-width columns | Start |
ui.scroll() |
Top to bottom, scrolling; horizontal after .flex_row() |
Start |
ui.card() |
Top to bottom, with the theme’s padding, spacing, surface, border and shadow | Start |
ui.container(style) |
Set by style |
Set by style |
- Spacing defaults to 0; set it with
.gap(…). - The window is itself a column the size of the content area, so widgets declared directly in
App::uistack from top to bottom. - A container without a
childrencall still takes part in layout and has no content. Use it for colored bars.
2. Sizing rules
Section titled “2. Sizing rules”Width and height each follow one rule (Sizing):
| Rule | How | Meaning |
|---|---|---|
| Fit | default | Just large enough for the content |
| Fixed | .w(240), .h(32), .size(240, 32) |
A fixed number of logical pixels |
| Fill | .w_fill(), .h_fill(), .fill() |
Fits the content, then takes the parent’s remaining space |
| Weighted | .w(Sizing::Grow(2.0)) |
Shares the remaining space by weight; Sizing::FILL is weight 1 |
| Fraction | .w(Sizing::Percent(0.5)) |
A fraction of the parent’s content area |
.min_w(…), .max_w(…), .min_h(…) and .max_h(…) limit a size under any rule. When the
minimum and maximum conflict, the minimum takes precedence. When a filling child reaches its
maximum, the remaining space goes to its siblings. Text inside a container with a maximum width
wraps at that width:
use cpui::Ui;
fn message(ui: &mut Ui<'_>, text: &str) { ui.column().max_w(320).p(12).bg_muted().rounded_lg().children(|ui| { ui.text(text); });}Fill and weighted sizes distribute only the space the parent already has. A parent that fits
its content has no remaining space, so w_fill() on its child has no effect. Give the parent a
fill or fixed size as well, and do the same for every ancestor up to the window.
use cpui::{Sizing, Ui};
fn columns(ui: &mut Ui<'_>) { ui.row().w_fill().gap(12).children(|ui| { ui.column().w(200).children(|ui| { ui.text("Fixed 200"); }); ui.column().w_fill().children(|ui| { ui.text("A third of the rest"); }); ui.column().w(Sizing::Grow(2.0)).children(|ui| { ui.text("Two thirds of the rest"); }); });}Two w_fill() children split the remaining space equally, but neither becomes narrower than its
content. Text inputs, number inputs, sliders, progress bars and tables fill by default, so in a
row with a button, an input takes all the space the button does not use:
use cpui::Ui;
fn search(ui: &mut Ui<'_>, query: &mut String) { ui.row().w_fill().gap(8).children(|ui| { ui.text_input(query).placeholder("Search"); ui.button("Go").primary(); });}Buttons, selects and text fit their content. Set .w(…) or .w_fill() for a different width.
3. Padding, spacing and alignment
Section titled “3. Padding, spacing and alignment”.p(16)pads all four sides,.px(16)the left and right,.py(8)the top and bottom, and.pt,.pr,.pband.plone side each. When every side differs, use.padding(Edges { … }). For one horizontal and one vertical value, useEdges::xy(16, 8)..gap(8)sets the space between neighboring children, and between lines when a row wraps..gap_x(…)and.gap_y(…)set the horizontal and vertical space separately..justify_start(),.justify_center(),.justify_end()and.justify_between()position the children along the direction..justify_around()and.justify_evenly()distribute the free space around them..items_start(),.items_center(),.items_end()and.items_stretch()position the children across the direction..center()centers them in both directions..items_baseline()on a row aligns the text of its children on a common baseline, regardless of their sizes. Use it for a large number beside a small label, or a label beside a text input..self_start(),.self_center(),.self_end()and.self_stretch()set the alignment of a single child across the direction. They apply to containers and to any widget:ui.button("Save").self_end().ui.spacer()takes the remaining space in its container and pushes the widgets after it to the far end..aspect_ratio(16.0 / 9.0)maintains the ratio of width to height. The height follows the width, or the width follows a fixed height..layout_priority(1.0)determines which children shrink first when a row does not fit. Text that can wrap or truncate narrows in order of priority, lowest first. For example, a file name stays whole while the path beside it is truncated..offset(x, y)shifts an element from the position its container assigns, without moving other elements. Use it for a badge that extends past a corner.
use cpui::Ui;
fn dialog_buttons(ui: &mut Ui<'_>) { ui.row().w_fill().gap(8).justify_end().children(|ui| { ui.button("Cancel"); ui.button("OK").primary(); });}
fn empty_state(ui: &mut Ui<'_>) { ui.column().fill().center().gap(8).children(|ui| { ui.heading("Nothing here yet"); ui.text("Click “New” to start.").muted(); });}
fn total(ui: &mut Ui<'_>, files: usize) { ui.row().items_baseline().gap(8).children(|ui| { ui.title(files); ui.text("files").muted(); });}Stacks
Section titled “Stacks”ui.stack() layers its children on top of each other. Later children cover earlier ones, and
the stack is as large as its largest child.
Each child is aligned independently, at the top left by default. Set justify_* (horizontal)
and items_* (vertical) on the stack to align all children, or .justify_self_*() and
.self_*() on a single child.
use cpui::Ui;
/// An avatar with a count in its top right corner.fn avatar(ui: &mut Ui<'_>, unread: u32) { ui.stack().children(|ui| { ui.row().size(40, 40).rounded(20).bg_muted().children(|_| {}); ui.badge(unread).self_start().justify_self_end(); });}A stack occupies space in the layout like any other container. For a layer that floats above the window’s content and takes no space, such as a menu, use an overlay.
4. Text
Section titled “4. Text”Text wraps to the width of its container according to standard line-breaking rules: CJK text
breaks between characters, and other text breaks at spaces. \n forces a line break. A
container without a fixed width narrows with its text, but not below the longest word.
Thai, Lao, Khmer and Myanmar are written without spaces between words. The word-break feature
breaks their lines at word boundaries. It is off by default because its dictionaries add about
1.1 MB to the program. Without it, such text breaks between any two characters.
cpui = { version = "0.1.1", features = ["word-break"] }ui.text(…).truncate()keeps the text on one line and truncates it with “…” when it does not fit. Text inui.listand table rows truncates by default.ui.text(…).text_align(Align::Center)centers or right-aligns each line within the text widget. This is visible only when the widget is wider than its text..text_sm(),.muted(),.text_color(…)and.text_size(…)on a container apply to the text and icons declared inside it, unless they set their own:
use cpui::Ui;
fn footer(ui: &mut Ui<'_>, seconds: f32) { ui.row().w_fill().px(16).py(8).gap(16).text_sm().muted().children(|ui| { ui.text(format_args!("Scanned in {seconds:.1} s")); ui.spacer(); ui.text("Press Enter to open"); });}5. Wrapping and grids
Section titled “5. Wrapping and grids”ui.flow() wraps to the next line when a row is full, and each child keeps its own width. Use
it for tags and button groups. .flex_wrap() makes any row wrap. .flex_row() and
.flex_col() set a container’s direction, for example based on the window width.
ui.grid(min_column_width) places its children in order into equal-width columns, as many as
fit. As the window narrows, the number of columns decreases, down to a single column.
use cpui::Ui;
fn overview(ui: &mut Ui<'_>) { ui.grid(240).gap(16).children(|ui| { for (name, value) in [("CPU", "12%"), ("Memory", "4.1 GB"), ("Disk", "38%")] { ui.card().children(|ui| { ui.text(name).muted(); ui.heading(value); }); } });}To choose a layout based on the available space, call ui.available_width(). It returns the
width of the container being declared, not of the window, so a piece of interface adapts
wherever it is placed: a row when wide, a column when narrow. When the width changes, the
interface is rebuilt within the same frame.
use cpui::{Style, Ui};
fn profile(ui: &mut Ui<'_>) { ui.column().w_fill().p(12).children(|ui| { let wide = ui.available_width() >= 320.0; let style = if wide { Style::row() } else { Style::column() }; ui.container(style.gap(12)).children(|ui| { ui.heading("Ada Lovelace"); ui.text("Mathematician").muted(); }); });}ui.grid_cols(n) always has n equal-width columns, regardless of width. A child with
.col_span(k) spans k columns, and moves to the next row when the current row has fewer columns
left.
use cpui::Ui;
fn settings(ui: &mut Ui<'_>, name: &mut String, note: &mut String) { ui.grid_cols(2).gap(12).children(|ui| { ui.text_input(name).placeholder("Name"); ui.button("Check").outline(); ui.text_input(note).placeholder("Note").col_span(2); });}6. Scrolling
Section titled “6. Scrolling”ui.scroll() scrolls vertically, or horizontally after .flex_row(). Its content does not
determine its size along the scrolling direction, so set one of the following:
h_fill(): a share of the remaining space.h(240): a fixed size.max_h(240): a maximum. The container is as tall as its content up to the maximum, and scrolls beyond it. Popups use this to stay inside the window.
Without any of these, it takes no space along the scrolling direction.
use cpui::Ui;
fn changelog(ui: &mut Ui<'_>, entries: &[String]) { ui.scroll().w_fill().h(240).p(12).gap(8).children(|ui| { for entry in entries { ui.text(entry); } });}use cpui::Ui;
fn suggestions(ui: &mut Ui<'_>, items: &[&str]) { // As tall as the items, at most 200; longer lists scroll. ui.scroll().w_fill().max_h(200).children(|ui| { for item in items { ui.text(item); } });}For many rows of equal height, use ui.list(rows).row_height(h).show(|ui, row| …), which
builds only the visible rows. For data with a header, use ui.table; its body also builds only
the visible rows.
7. Overlays
Section titled “7. Overlays”ui.overlay(place) declares a container that floats above other content. It takes no space in
its parent, is not clipped by it, and is moved back inside the window when it would extend past
the edge. Place sets the position:
| Value | Position |
|---|---|
Place::Below(rect) |
Below the rectangle, left-aligned with it; above it when there is no room below |
Place::At(x, y) |
Top-left corner at a position in the window |
Place::Center |
The middle of the window |
Place::Fill |
Fills the window |
The rectangle usually comes from a widget’s Response::rect. Tooltips, popovers, context menus
and dialogs are built on overlays; in most cases, use .tooltip(…), ui.popover,
ui.context_menu and ui.dialog instead of ui.overlay.
use cpui::{Place, Ui};
fn hint(ui: &mut Ui<'_>, visible: bool) { let help = ui.button("Help").response(); if visible { let tip = ui.overlay(Place::Below(help.rect())).p(12).bg_surface(); tip.bordered().rounded_lg().children(|ui| { ui.text("Press F1 for the full help."); }); }}8. Appearance
Section titled “8. Appearance”Containers also set their own appearance:
| Method | Effect |
|---|---|
.bg(color), .bg_muted(), .bg_surface() |
Background color; the named ones use the theme’s muted and surface colors |
.rounded(radius), .rounded_sm(), .rounded_md(), .rounded_lg(), .rounded_full() |
Rounded corners; the named sizes are the theme’s radii |
.border(width, color), .bordered() |
Border; .bordered() is 1 pixel wide in the theme’s border color |
.shadow(blur, offset, color), .shadow_sm(), .shadow_md(), .shadow_lg() |
Shadow; the named sizes use the theme’s shadow color |
.ring(width, color) |
A ring outside the border, used as a focus ring |
.opacity(0–1) |
Opacity of the container and everything inside it |
.overflow_hidden() |
Clips children that extend beyond the container’s bounds |
.disabled(true) |
Disables every widget inside |
.when(condition, |c| …), .when_some(option, |c, v| …) |
Applies settings only when a condition holds |
.hover(|s| …), .active(|s| …), .focus_within(|s| …) |
The appearance while hovered, while pressed, or while a control inside has focus; see below |
Interaction states
Section titled “Interaction states”A container can change its appearance while the pointer is over it, while it is pressed, or while a control inside it has keyboard focus. The closure can change the background, border, radius, shadow, ring and opacity. The change transitions over the theme’s motion duration. Call these methods after all other style methods. The pointer over a widget inside the container counts as over the container.
For a card or row that is clicked as a whole, use children_with_response, which also returns
the container’s Response. A click on a widget inside goes to that widget.
use cpui::Ui;
fn option(ui: &mut Ui<'_>, name: &str, selected: bool) -> bool { let t = ui.theme(); let border = if selected { t.accent } else { t.border }; let card = ui.column().w_fill().p(12).border(1, border).rounded_md(); let card = card.hover(|s| s.bg(t.muted)).active(|s| s.bg(t.secondary)); let (_, card) = card.children_with_response(|ui| { ui.text(name).font_bold(); }); card.clicked()}Other colors come from the theme. Read it with let t = ui.theme(); before starting a chain,
because the chain borrows ui. See theming.md.
To define a style once and reuse it, write a function that returns a Style and place it with
ui.container. Style has the same methods as a container, except those that read the theme:
use cpui::{Style, Theme, Ui};
fn panel(t: &Theme) -> Style { Style::column().w(280).h_fill().p(16).gap(12).bg(t.muted)}
fn sidebar(ui: &mut Ui<'_>) { let t = ui.theme(); ui.container(panel(&t)).children(|ui| { ui.heading("Rules"); });}9. A common page structure
Section titled “9. A common page structure”A sidebar with a content area: the outermost container fills the window, the sidebar has a fixed width, and the content area takes the remaining space and scrolls.
use cpui::Ui;
fn page(ui: &mut Ui<'_>, section: &mut usize) { ui.row().fill().items_stretch().children(|ui| { ui.column().w(200).p(12).gap(4).bg_muted().children(|ui| { for (i, name) in ["General", "Appearance", "About"].into_iter().enumerate() { let button = ui.button(name).w_fill().when(*section != i, |b| b.ghost()); if button.clicked() { *section = i; } } }); ui.scroll().fill().p(24).gap(12).children(|ui| { ui.title("Settings"); ui.text("The chosen section's content goes here."); }); });}For a sidebar the user can resize, use ui.resizable. It takes the width of the first pane as a
&mut f32 and updates it while the divider is dragged. The two panes are declared in sequence,
so each closure can borrow application state.
use cpui::Ui;
fn page(ui: &mut Ui<'_>, sidebar: &mut f32, section: &mut usize) { ui.resizable(sidebar) .min(140) .max(360) .first(|ui| { ui.column().fill().p(12).gap(4).children(|ui| { for (i, name) in ["General", "Appearance", "About"].into_iter().enumerate() { let button = ui.button(name).w_fill().when(*section != i, |b| b.ghost()); if button.clicked() { *section = i; } } }); }) .second(|ui| { ui.scroll().fill().p(24).gap(12).children(|ui| { ui.title("Settings"); }); });}.vertical() arranges the panes from top to bottom; size is then the height of the first
pane. A split fills the space it is given, so place it in a container that has a size, or at the
top level of the window.
10. Troubleshooting
Section titled “10. Troubleshooting”| Symptom | Cause and fix |
|---|---|
w_fill() does not widen |
The parent fits its content, so it has no remaining space. Give the parent w_fill() or a fixed width as well |
| A scroll container takes no space | Its content does not determine its size along the scrolling direction. Use h_fill(), a fixed height or max_h() |
| Focus jumps to a neighboring list item | The list grows, shrinks or reorders, and its items have no keys. Wrap each item in ui.key |
| Text does not wrap | Its container has no width limit, or the text is in a ui.list or table row. Give the container a width |
| A child of a row is not as tall as the row | Rows center their children. Set .items_stretch() on the row |