Container widget wraps a single child element and provides control over alignment, padding, and styling. It’s essential for creating well-structured layouts.
Basic Usage
Builder Methods
new(content: impl Into<Element>)
Creates a new container with the given content.
padding(padding: impl Into<Padding>)
Sets the padding around the content.
width(width: impl Into<Length>)
Sets the container width.
height(height: impl Into<Length>)
Sets the container height.
max_width(max_width: impl Into<Pixels>)
Sets the maximum width.
max_height(max_height: impl Into<Pixels>)
Sets the maximum height.
Alignment Methods
center(length: impl Into<Length>)
Centers content both horizontally and vertically.
center_x(width: impl Into<Length>)
Centers content horizontally.
center_y(height: impl Into<Length>)
Centers content vertically.
align_x(alignment: alignment::Horizontal)
Sets horizontal alignment.
align_y(alignment: alignment::Vertical)
Sets vertical alignment.
Helper Methods
clip(clip: bool)
Sets whether content should be clipped on overflow.
style(style_fn: impl Fn(&Theme) -> Style)
Applies custom styling.
Built-in Styles
container::transparent
No background or border (default).
container::rounded_box
Rounded corners with a background.
container::bordered_box
Background with a border.
container::dark
Dark background with white text.
Semantic Styles
container::background
Custom background color.
Style Structure
Common Patterns
Card Layout
Centered Dialog
Sidebar Layout
Header Section
Status Banner
Tips and Best Practices
- Use containers for spacing - Add padding and alignment to single elements
- Combine with Row/Column - Containers work well inside layout widgets
- Style consistently - Use built-in styles for visual consistency
- Mind the width/height - Containers don’t have intrinsic size
- Use max_width for readability - Limit content width on wide screens
- Clip when needed - Prevent content overflow with
.clip(true)
Related Widgets
- Row/Column - For multiple children
- Scrollable - For scrollable containers
- Button - Similar styling options
