1.9 KiB
1.9 KiB
| title | alt_titles | ||||||
|---|---|---|---|---|---|---|---|
| How do I center a widget in a screen? |
|
To center a widget within a container use
align. But remember that
align works on the children of a container, it isn't something you use
on the child you want centered.
For example, here's an app that shows a Button in the middle of a
Screen:
from textual.app import App, ComposeResult
from textual.widgets import Button
class ButtonApp(App):
CSS = """
Screen {
align: center middle;
}
"""
def compose(self) -> ComposeResult:
yield Button("PUSH ME!")
if __name__ == "__main__":
ButtonApp().run()
If you use the above on multiple widgets, you'll find they appear to "left-align" in the center of the screen, like this:
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
If you want them more like this:
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
the best approach is to wrap each widget in a container that individually centers it. For example:
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button
class Center( Container ):
DEFAULT_CSS = """
Center {
height: auto;
width: 100%;
align: center middle;
}
"""
class ButtonApp(App):
CSS = """
Screen {
align: center middle;
}
"""
def compose(self) -> ComposeResult:
yield Center(Button("PUSH ME!"))
yield Center(Button("AND ME!"))
yield Center(Button("ALSO PLEASE PUSH ME!"))
yield Center(Button("HEY ME ALSO!!"))
if __name__ == "__main__":
ButtonApp().run()