src/content/docs/recipes/layout/center-a-widget.md
You want to center a widget within some area of your TUI's layout.
To center a widget in any area, create a Rect that is centered within the area. You can
calculate the x and y positions of the widget by subtracting the widget width and height from the
enclosing area's width and height, respectively, and dividing by 2.
More simply, you can use the .centered_vertically() and .centered_horizontally() methods on
Rect.
{{ #include @code/recipes/how-to-misc/src/layout.rs:imports }}
{{ #include @code/recipes/how-to-misc/src/layout.rs:horizontal }}
{{ #include @code/recipes/how-to-misc/src/layout.rs:imports }}
{{ #include @code/recipes/how-to-misc/src/layout.rs:vertical }}
You can use the .centered method to get a centered Rect.
{{ #include @code/recipes/how-to-misc/src/layout.rs:center }}
You can use these methods to draw any widget centered on the containing area.
{{ #include @code/recipes/how-to-misc/src/layout.rs:render }}
A common use case for this feature is to create a popup style dialog block. For this, typically,
you'll want to use the [Clear] widget to clear the popup area before rendering your content to it.
The following is an example of how you might do that:
{{ #include @code/recipes/how-to-misc/src/layout.rs:render_popup }}
Center a widget by placing it inside a Rect that sits in the middle of the area. Compute that rect
by hand or use the .centered, .centered_horizontally(), and .centered_vertically() helpers on
Rect, then render the widget (popups included) into it.
:::note
There is no method for vertically aligning text within an area yet. We recommend prewrapping the text using the textwrap crate and then using the line count to work out where to render the text.
:::
Full code for this recipe is available in the website repo at: https://github.com/ratatui/ratatui-website/blob/main/code/recipes/how-to-misc/src/layout.rs
There are several third party widget libraries for making popups easy to use: