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

如何让main与div#undermain占据布局剩余高度?

如何让main及子元素占据布局剩余高度(Tailwind实现)

我尝试让main元素和div#undermain占据布局的剩余高度,但没能实现,使用Tailwind的代码如下:

<body>
  <div class="min-h-screen w-screen overflow-auto bg-black">
    <nav
      class="flex w-full items-center justify-start gap-3 border-b-2 border-b-gray-800 py-3 pr-6 pl-3"
    >
      <img src="./someurl.svg" />
      <h1 class="text-2xl text-green-500">Delivert</h1>
    </nav>
    <main class="h-full w-full">
      <div id="undermain" class="flex h-full w-full items-center justify-center">
        <button class="bg-green-500">
          sign in
        </button>
      </div>
    </main>
  </div>
</body>

我知道flexbox是解决这类问题的常用方法,自己试出了一个可行方案:

  • 给body下的最外层div设置display: flex和flex-direction: column;
  • 给main设置flex-grow: 1和display: flex;
  • 移除#undermain的height: 100%。

但我觉得这个方案不符合CSS规范,想知道更合理的实现方式。


其实这个方案完全符合CSS规范,flexbox就是专门用来处理这种弹性布局场景的。下面是用Tailwind工具类直接实现的优化代码:

<body>
  <div class="min-h-screen w-screen overflow-auto bg-black flex flex-col">
    <nav
      class="flex w-full items-center justify-start gap-3 border-b-2 border-b-gray-800 py-3 pr-6 pl-3"
    >
      <img src="./someurl.svg" />
      <h1 class="text-2xl text-green-500">Delivert</h1>
    </nav>
    <main class="flex-grow flex w-full">
      <div id="undermain" class="flex w-full items-center justify-center">
        <button class="bg-green-500">
          sign in
        </button>
      </div>
    </main>
  </div>
</body>

实现说明:

  • 最外层div添加flex flex-col类,让nav和main两个子元素按垂直方向排列;
  • 给main添加flex-grow类,对应CSS的flex-grow: 1,让它自动占据nav以外的所有剩余高度;
  • main设置flex类,使其成为flex容器,此时子元素#undermain会默认拉伸填充容器高度,不需要额外设置h-full,直接用flex items-center justify-center就能实现内容居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:58:14