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

Tailwind CSS如何实现flex容器内按钮垂直居中对齐

Tailwind CSS 调整按钮垂直居中实现方法

问题背景

开发组件时按钮默认停靠在容器顶部,需要调整为垂直居中对齐,组件运行效果如下:
组件效果截图
当前业务代码如下:

<div class="flex flex-grow mb-4">
  <div class="w-12">
    <i  class=" cursor-pointer el-icon-back text-white mr-2 bg-blue-600 rounded-full p-2 mr-2" ></i>
  </div>

  <div class="w-96 border-gray-400 flex flex-row">
    <div class="transition duration-500 shadow ease-in-out transform hover:-translate-y-1 hover:shadow-sm select-none cursor-pointer bg-white dark:bg-gray-800 rounded-md flex flex-1 items-center p-4 hover:border hover:border-blue-400">
        <div class="flex flex-col w-10 h-10 justify-center items-center mr-4">
            <a href="#" class="block relative">
                <img alt="profil" src="https://www.tailwind-kit.com/images/person/6.jpg" class="mx-auto object-cover rounded-full h-10 w-10 "/>
            </a>
        </div>
        <div class="flex-1 pl-1 ">
            <div class="font-medium dark:text-white">
                jake li
            </div>
            <div class="text-gray-600 dark:text-gray-200 text-sm">
                2022.1.11
            </div>
        </div>
        <div class="text-gray-600 dark:text-gray-200 text-xs">
        
        </div>
        <button class="w-12 text-right flex justify-end opacity-0 hover:opacity-100">
        </button>
    </div>
</div>

调整方案

按钮靠顶的核心原因是:按钮本身设置了flex布局,仅配置了水平方向右对齐(justify-end),未配置垂直方向对齐规则;虽然外层卡片容器已经加了items-center,但按钮作为flex容器自身的内容对齐规则缺失,就会出现顶部对齐的问题。
可任选以下一种方式修改:

  • 方式一:给按钮class添加items-center,利用flex容器交叉轴对齐规则实现内部内容垂直居中,修改后按钮代码:
<button class="w-12 text-right flex justify-end items-center opacity-0 hover:opacity-100">
</button>
  • 方式二:给按钮class添加self-center,强制按钮作为父flex容器的子项沿交叉轴居中,不需要调整按钮自身的flex布局规则,修改后按钮代码:
<button class="w-12 text-right flex justify-end self-center opacity-0 hover:opacity-100">
</button>

补充:原代码返回按钮icon上重复写了两次mr-2类,属于冗余代码,不影响居中效果可按需清理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:48:39