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

如何在容器div中居中左对齐的多行标题文本

如何在容器div中居中左对齐的多行标题文本

我完全懂你的困扰!你想要让多行左对齐的标题整体在容器里居中,但又不想给标题设置固定宽度(比如max-w-md那种),而是希望标题的宽度自动适配最宽的那一行,这样文本看起来才是真正的居中,对吧?

其实解决方法很简单,核心就是让标题的容器收缩到内容的宽度,而不是占满父容器的宽度。你只需要调整一下包裹h1的那个div的类:

把原来的<div class="text-left">改成<div class="inline-block text-left">。

修改后的完整代码:

<div class="min-w-screen flex h-full min-h-screen w-full flex-row-reverse bg-black">
  <div class="flex items-center justify-center bg-black p-4 lg:w-1/2 lg:p-10">
    <div class="inline-block text-left">
      <h1 class="text-balance font-sans text-6xl text-white">
        This is a long title so it breaks into another line. <br />
        This is another line.
      </h1>
    </div>
  </div>
  <div class="bg-white lg:w-1/2">
    Container
  </div>
</div>

原理说明:

  • inline-block会让元素的宽度由内部内容的最大宽度决定(也就是你标题里最宽的那一行的宽度),而不是默认块级元素的占满父容器宽度。
  • 外层的flex items-center justify-center已经负责了水平和垂直居中,当包裹标题的容器变成inline-block后,它就会被居中对齐,同时内部的text-left保持标题文本左对齐,完美实现你想要的效果!

备注:内容来源于stack exchange,提问作者Thore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 12:12:58