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

React+Tailwind CSS无法居中Div问题求助

解决React + Tailwind CSS中Div无法居中的问题

你的问题出在右侧包含登录表单的div没有占据父容器的剩余宽度,导致justify-center只在自身内容宽度范围内生效,视觉上呈现靠左对齐的效果。

修复方案

给包含登录表单的外层div添加flex-1类,让它占据父flex容器中除logo区域外的所有剩余水平空间。修改后的完整代码如下:

"use client";
import Image from "next/image";
import React from "react";

const LoginPage = () => {
  return (
    <div className="flex h-screen">
      <div className="flex-shrink-0 p-4">
        <Image
          src="/big-logo-black-ai.svg"
          alt="Logo"
          className="w-12 h-12"
          width={400}
          height={40}
        />
      </div>

      {/* 添加 flex-1 类占据剩余空间 */}
      <div className="flex-1 flex justify-center items-center">
        <div className="w-full max-w-md">
          <h1 className="text-2xl font-bold mb-4">Login</h1>
          <form>
            <div className="mb-4">
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700"
              >
                Email
              </label>
              <input
                type="email"
                id="email"
                name="email"
                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring focus:border-blue-500"
                placeholder="you@example.com"
              />
            </div>
            <div className="mb-4">
              <button
                type="submit"
                className="w-full bg-blue-500 text-white rounded-md py-2 font-semibold hover:bg-blue-600"
              >
                Submit
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;

原理说明

  • 父容器flex h-screen设置了横向flex布局且高度占满屏幕
  • 第一个div的flex-shrink-0属性确保logo区域不会被压缩,保持固定宽度
  • 给第二个div添加flex-1后,它会自动填充父容器中剩余的全部水平空间,此时justify-center和items-center就能在整个剩余区域内实现内容居中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:04:59