Nicegui 组件放在页面中间

可以使用以下方法将 组件 放在页面中间:

方法1:使用 ui.column() 居中对齐

python 复制代码
with ui.column().classes('absolute-center items-center'):
    with ui.card():
        ui.label('卡片内容')
        # 其他卡片内容...

方法2:使用 CSS 类

python 复制代码
with ui.card().classes('mx-auto my-auto'):
    ui.label('卡片内容')
    # 其他卡片内容...

方法3:更灵活的布局控制

python 复制代码
with ui.row().classes('w-full h-screen justify-center items-center'):
    with ui.card().classes('w-96'):
        ui.label('卡片内容')
        ui.input(label='输入框')
        ui.button('提交')

方法4:响应式居中

python 复制代码
with ui.column().classes('absolute-center items-center w-full max-w-md'):
    with ui.card().classes('w-full'):
        ui.label('居中卡片')
        with ui.row():
            ui.button('确定')
            ui.button('取消')

方法5:使用网格布局

python 复制代码
with ui.grid(columns=1).classes('h-screen place-items-center'):
    with ui.card():
        ui.label('网格居中卡片')
        # 卡片内容...

完整示例

python 复制代码
from nicegui import ui

# 方法1:推荐使用
with ui.column().classes('absolute-center items-center'):
    with ui.card().classes('w-96 shadow-lg'):
        ui.label('登录').classes('text-2xl font-bold text-center')
        ui.input(label='用户名').classes('w-full')
        ui.input(label='密码', password=True).classes('w-full')
        ui.button('登录', color='primary').classes('w-full')

ui.run()

说明:

  • absolute-center:水平和垂直居中
  • items-center:水平居中(在 column 中)
  • justify-center:垂直居中(在 row 中)
  • mx-auto:水平居中
  • my-auto:垂直居中
  • h-screen:全屏高度
  • w-full:全宽度

选择适合你需求的方法即可。方法1和2最简洁,方法3最灵活。

相关推荐
北城笑笑1 天前
FPGA 与 市场主流芯片分类详解:SoC/CPU/GPU/DPU 等芯片核心特性与工程应用
前端·单片机·fpga开发·fpga
A923A1 天前
【从零开始学 React | 第四章】useEffect和自定义Hook
前端·react.js·fetch·useeffect
ZC跨境爬虫1 天前
批量爬取小说章节并优化排版(附完整可运行脚本)
前端·爬虫·python·自动化
ZC跨境爬虫1 天前
海南大学交友平台登录页开发实战day4(解决python传输并读取登录信息的问题)
开发语言·前端·python·flask·html
来一颗砂糖橘1 天前
pnpm:现代前端开发的高效包管理器
前端·pnpm
前端摸鱼匠1 天前
Vue 3 的defineProps编译器宏:详解<script setup>中defineProps的使用
前端·javascript·vue.js·前端框架·ecmascript
木斯佳1 天前
前端八股文面经大全: 美团财务科技前端一面 (2026-04-09)·面经深度解析
前端·实习面经·前端初级
LIO1 天前
React 零基础入门,一篇搞懂核心用法(适合新手)
前端·react.js
TeamDev1 天前
JxBrowser 8.18.2 版本发布啦!
java·前端·跨平台·桌面应用·web ui·jxbrowser·浏览器控件
netkiller-BG7NYT1 天前
yoloutils - Openclaw Agent Skill
前端·webpack·node.js