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

React+Tailwind按钮无法居中对齐?求无需冗余段落的解决办法

解决按钮居中问题的方案

问题根源在于包裹按钮的内层div默认仅占内容宽度,因此无法让按钮在父容器的水平中心对齐。添加长段文本后,该div被撑满外层容器宽度,按钮自然就能居中。无需多余文本的话,有两种简单的Tailwind方案:

方案1:使用文本居中类

给包裹按钮的div添加text-center类,利用行内元素的文本居中特性:

const Skills = () => {
    return (
        <div className="w-full p-2 flex items-center py-16 bg-blue-50">
            <div className="max-w-[1240px] m-auto">
                <div className="text-center">
                    <button className="shadow-xl bg-gradient-to-r from-[#5651e5] to-[#709dff] text-white rounded-md p-2 mx-2">Skills</button>
                    <button className="shadow-xl bg-gradient-to-r from-[#5651e5] to-[#709dff] text-white rounded-md p-2 mx-2">Hobbies</button>
                </div>
            </div>
        </div>
    )
}

方案2:使用Flex布局居中

给包裹按钮的div添加flex justify-center类,通过Flex布局实现水平居中,这种方式更灵活,适合后续调整按钮排列:

const Skills = () => {
    return (
        <div className="w-full p-2 flex items-center py-16 bg-blue-50">
            <div className="max-w-[1240px] m-auto">
                <div className="flex justify-center">
                    <button className="shadow-xl bg-gradient-to-r from-[#5651e5] to-[#709dff] text-white rounded-md p-2 mx-2">Skills</button>
                    <button className="shadow-xl bg-gradient-to-r from-[#5651e5] to-[#709dff] text-white rounded-md p-2 mx-2">Hobbies</button>
                </div>
            </div>
        </div>
    )
}

两种方案都能让按钮在不添加多余段落的情况下,水平居中对齐到外层容器的中心位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:27