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

如何用Flexbox让两栏内容从同一垂直线起点对齐

解决两栏布局标题行数不同时描述文本对齐的问题

不用给标题设置min-height,你可以用CSS Grid布局实现需求——把每个子组件的内容容器改成网格结构,让标题、链接组等对应区块在两栏中自动对齐高度,不管标题是1行还是多行,描述都会从同一垂直线开始。

修改后的代码如下:

export default function App() {
  const Child = ({ backgroundColor, title, desc }) => {
    return (
      <div className={`relative flex-1 ${backgroundColor} p-4`}>
        <div className="h-full overflow-hidden border-2 bg-white pb-20 flex flex-col justify-between">
          {/* 核心修改:将内容容器改为Grid布局,定义行结构 */}
          <div className="p-4 flex-1 grid grid-template-rows: auto auto auto 1fr gap-2">
            <img src="https://picsum.photos/250/250" />
            <h2 className="font-Headingg text-2xl font-bold text-black">{title}</h2>
            <div className="flex flex-wrap text-black">
              <span className="mr-2">Link 1</span>
              <span>Link 2</span>
            </div>
            <p className="text-md text-justify text-black">{desc}</p>
          </div>
          <div className="absolute bottom-0 flex flex-wrap items-center bg-slate-300 p-4">
            <p className="mb-2 mr-2 px-1 py-2 text-xs tracking-wide">Link #1</p>
            <p className="mb-2 mr-2 px-1 py-2 text-xs tracking-wide">Link #2</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="container mx-auto p-6">
        <div className="-mx-4 flex flex-shrink">
          <Child title="some title text" desc="some description" backgroundColor={'bg-yellow-200'} />
          <Child title="some title text which is longer which should cover atleast 2 lines" desc="a  description that is longer than the other description, but description should start on same point in both columns " backgroundColor={'bg-cyan-200'} />
        </div>
      </div>
    </>
  )
}

关键修改说明:

  • 把原flex-1的内容容器改为grid布局,通过grid-template-rows: auto auto auto 1fr定义四行:
    • 图片、标题、链接组行用auto自适应高度,两栏会自动取最长的对应区块高度统一该行高度
    • 描述行用1fr占据剩余空间,确保描述从同一垂直线位置开始
  • 用gap-2替代原有的mb-2、mb-4,统一控制网格行间距,避免多余外边距干扰布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:27:26