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

TailwindCSS与React布局对齐问题:PlanCard垂直错位修复

解决PlanCard组件错位问题

你的问题出在flex容器的垂直对齐设置上,加上卡片高度未强制统一,导致第一个卡片出现错位。按以下步骤修改即可解决:

1. 修改顶层容器的对齐方式

将顶层代码中bg-red-200的div的items-center替换为items-stretch。这个属性会让flex容器内的所有子元素(也就是PlanCard)拉伸到同一高度,从根源避免高度不一致导致的错位。

修改后的顶层代码:

import PlanCard from '../components/PlanCard';

export default function Plans()
{
    return (
        <div className='bg-slate-200 flex justify-center items-center h-full p-8 overflow-y-auto h-128'>
            <div className='bg-red-200 flex flex-row items-stretch space-x-8 p-2 space-y-8'>
                <PlanCard name='Basic' price='0.99' description='Good for those only interested in summaries for one topic.' features={['1 topic per month']} id={0} />
                <PlanCard name='Basic' price='0.99' description='Good for those only interested in summaries for one topic.' features={['1 topic per month']} id={0} />
                <PlanCard name='Basic' price='0.99' description='Good for those only interested in summaries for one topic.' features={['1 topic per month']} id={0} />
            </div>
        </div>
    );
}

2. 强制PlanCard占满父容器高度

给PlanCard组件的根div添加h-full类,确保卡片能完全占满父容器分配的高度,让内部的flex布局(尤其是grow属性的容器)正确填充空余空间,保证所有卡片的内部布局一致。

修改后的PlanCard代码:

import { useNavigate } from "react-router-dom";

export default function PlanCard({ name, price, description, features, id })
{
    const navigate = useNavigate();
    const button_style_string = 'bg-purple-300 text-center hover:bg-black text-black font-bold py-2 px-4 border-2 border-black hover:border-transparent hover:text-white rounded-full cursor-pointer mx-2';

    const on_free_trial = () =>
    {
        navigate('/signup?p=' + id);
    }

    return (
        <div className='bg-gray-400 flex flex-col h-full border-2 border-black rounded-lg'>
            <div className='flex flex-col grow p-8 gap-4'>
                <h2 className='text-2xl font-bold'>{name}</h2>
                <h3 className='text-xl font-bold'>${price + '/month'}</h3>
                <p className='text-lg'>{description}</p>
            </div>
            <div className='flex flex-col p-8 gap-4'>
                <ul>
                    {features.map((feature, index) => <li key={index}>{'- ' + feature}</li>)}
                </ul>
                <button className={button_style_string} onClick={on_free_trial}>Start Free Trial!</button>
            </div>
        </div>
    );
}

原理说明

之前用items-center会让卡片按自身高度垂直居中,哪怕内容完全一致,渲染时的细微差异(比如文字换行、默认边距)也会导致高度不同,进而出现错位。改成items-stretch后,所有卡片被强制拉到同一高度,再配合h-full确保卡片内部布局填充完整,就能实现完美的水平和垂直对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:55:19