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

Flexbox中justify-content与align-items属性失效问题求助

Flex布局属性不生效的原因与修复方案

你的问题核心是:需要使用Flex布局的子div没有添加flex类。Tailwind中,flex-col、justify-center这类Flex相关属性,必须在元素被标记为Flex容器(即添加flex类)的前提下才能生效。

看你的代码,左右两个子div只添加了flex-col,却缺少了关键的flex类,导致justify-center完全不起作用。

修复后的代码

{/* container */}
<div className="w-screen relative mb-10">
        // background div that provides a colour background to only the left half of the parent div
        <div
          id="backgroundShape"
          className="w-1/2 bg-grey-400 absolute h-full -z-20"
        ></div>
        // div that holds the actual text and image content for the foreground
        <div className="mx-auto container px-6 xl:px-28 flex py-10">
        // left half of content, this gets displayed over the background div
          <div className="w-1/2 flex flex-col justify-center pr-20 ">
            <div>
              Heading 1
            </div>
            <div className="text-4xl">
              Heading 2
            </div>
            <div className="grid grid-cols-2 grid-rows-2 gap-x-6  gap-y-3">
              <div>
                <FaScroll className="" />
                <h3 className="text-lg">
                  Subheader
                </h3>
                <p className="text-sm">
                  Description
                </p>
              </div>
            </div>
          </div>

          // right half of content displaying two images in a column
          <div className="w-1/2 flex flex-col pl-10 justify-center">
            <div>
              <img
                src="https://www.w3schools.com/images/w3schools_green.jpg"
                alt="image"
              />
            </div>
            <div>
              <img
                src="https://www.w3schools.com/images/w3schools_green.jpg"
                alt="image"
              />
            </div>
          </div>
        </div>
      </div>

关键修改说明

  • 给左侧内容div添加flex类:className="w-1/2 flex flex-col justify-center pr-20 "
  • 给右侧内容div添加flex类:className="w-1/2 flex flex-col pl-10 justify-center"

添加flex类后,元素成为Flex容器,flex-col会将主轴设置为垂直方向,justify-center就能正常控制子元素在主轴方向上的居中对齐了。如果需要子元素在交叉轴方向(水平)居中,还可以额外添加items-center类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:07:03