You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Next.js+Tailwind元素实现垂直水平双向居中?

解决Next.js首页元素上下左右双向居中问题

你的代码里元素仅实现左右居中,是因为h-full依赖父元素的高度,但默认情况下html和body并未设置满屏高度,导致justify-center无法生效。可以通过以下两种方式修改:

方案1:直接修改Home组件的main容器类名

将h-full替换为min-h-screen,让main容器直接占满整个视口高度:

import { Button } from "@/components/ui/button";
import Link from "next/link";

export default function Home() {
  return (
    <main className="flex flex-col justify-center min-h-screen text-center max-w-5xl mx-auto gap-6">
      <h1 className="text-5xl font-bold">Invoicipedia</h1>
      <p>
        <Button asChild>
          <Link href="/dashboard">Login</Link>
        </Button>
      </p>
    </main>
  );
}

方案2:确保根布局的html/body设置满屏高度

如果想保留h-full,需要在根布局文件(app/layout.jsx)中给html和body添加高度样式:

export default function RootLayout({ children }) {
  return (
    <html lang="en" className="h-full">
      <body className="h-full">{children}</body>
    </html>
  );
}

完成上述修改后,页面元素即可实现上下左右双向居中。

内容的提问来源于stack exchange,提问作者Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 07:18:10