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

如何创建带最大宽度的居中div容器?

解决Tailwind内容居中并限制最大宽度的问题

你的代码问题出在两个核心点:

  • flex容器默认是行布局(flex-row),导致<h2>和<p>会尝试并排显示,直接破坏了垂直排版结构
  • 仅用justify-center只能让flex子元素在容器内居中,但容器本身没有实现水平居中,且子元素会自动撑满容器宽度

修正方案一:简洁版(无需flex)

这种方式更适合垂直排版的内容,直接通过边距自动实现容器居中,同时限制最大宽度:

<main class="pt-20">
  <div class="max-w-lg mx-auto">
    <h2 class="text-5xl font-semibold tracking-tight text-center text-gray-700">
      A Cool Title
    </h2>
    <p class="mt-8 text-sm text-center text-gray-700">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
</main>

修正方案二:保留flex布局的调整版

如果必须使用flex,需要添加flex-col让子元素垂直排列,同时用mx-auto让flex容器本身水平居中:

<main class="pt-20">
  <div class="flex flex-col justify-center max-w-lg mx-auto">
    <h2 class="text-5xl font-semibold tracking-tight text-center text-gray-700">
      A Cool Title
    </h2>
    <p class="mt-8 text-sm text-center text-gray-700">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
</main>

两种方案都能实现:内容容器水平居中,最大宽度限制为lg(1024px),大屏幕下不会出现内容过度拉伸的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:55:15