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

Tailwind CSS中justify-center在flex-row生效,flex-col下为何失效?

Flex Column布局中子元素无法水平居中的问题解决

在Nuxt.js项目用Tailwind CSS做布局时碰到个问题:给容器加flex flex-col justify-center类后,子元素没法水平居中,但删掉flex-col(默认是flex-row布局)就正常显示。

原代码如下:

<script setup></script>
<template>
  <div class="bg-slate-800">
    <div class="h-48"></div>
    <div class="flex flex-col justify-center">
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
    </div>
  </div>
</template>

添加flex-col时,子元素垂直排列但整体靠左;移除flex-col后,子元素能水平居中排列。

问题原因

flex-col把flex容器的主轴设为垂直方向(Y轴),这时候justify-center管的是垂直方向的居中对齐;而你要的是子元素在水平方向(交叉轴)的居中,这时候得加items-center来控制交叉轴的对齐方式。

解决方案

修改flex容器的类,加上items-center就行,完整代码:

<script setup></script>
<template>
  <div class="bg-slate-800">
    <div class="h-48"></div>
    <div class="flex flex-col justify-center items-center">
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
      <div class="h-40 w-20 ">
        <h1 class="text-white">Hi</h1>
      </div>
    </div>
  </div>
</template>

简单说下各属性作用:

  • flex-col:设置主轴为垂直方向,子元素垂直排列
  • justify-center:让子元素在垂直方向上居中
  • items-center:让子元素在水平方向上居中

内容的提问来源于stack exchange,提问作者Erdem Öztürk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:21:10